create an nstextfield with text based nstextattachments in swift

To create an NSTextField with text based NSTextAttachments in Swift, you need to use NSAttributedString.

Here’s an example code snippet:

let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 100))

let textAttachment = NSTextAttachment()
textAttachment.image = NSImage(named: "myImage")

let attributedString = NSAttributedString(attachment: textAttachment)
let attributedStringWithText = NSMutableAttributedString(string: "Hello, ")
attributedStringWithText.append(NSAttributedString(string: " World!"))

textField.attributedStringValue = attributedStringWithText
498 chars
12 lines

This code creates an NSTextField, sets an NSTextAttachment with an image and creates an NSAttributedString from it. It then creates a NSMutableAttributedString and builds it by appending the NSAttributedString with the NSTextAttachment, and then appends a normal string. Finally, the NSMutableAttributedString is set as the attributedStringValue of the NSTextField.

gistlibby LogSnag