Mac OSX - 资料

NSTextField设置富文本-文本添加点击事件:

来源:http://howtodevelop.eu/question/xcode-swift-with-xcode-8-color-attribute-is-ignored-in-nsattributedstring-with-nslinkattributename,34111

代码:import Cocoa

protocol MyTextFieldDelegate {

func changeNodeClicked()

}

class MyTextField: NSTextField {

var mydelegate: MyTextFieldDelegate?

var referenceView: NSTextView {

let theRect = self.cell!.titleRect(forBounds: self.bounds)

let tv = NSTextView(frame: theRect)

tv.textStorage!.setAttributedString(self.attributedStringValue)

return tv

}

override func mouseDown(with event: NSEvent) {

let point = self.convert(event.locationInWindow, from: nil)

let charIndex = referenceView.textContainer!.textView!.characterIndexForInsertion(at: point)

//        if charIndex < self.attributedStringValue.length {

let attributes = self.attributedStringValue.attributes(at: charIndex, effectiveRange: nil)

if let link = attributes[NSLinkAttributeName] as? String ,link=="changeNode"{

// ...

self.mydelegate?.changeNodeClicked()

return

}

//        }

super.mouseDown(with: event)

}

}

使用自定义的MyTextField类创建textfield:

let str = NSMutableAttributedString(string: "\(mgr.localizedDescription!)  切换节点")

str.addAttribute(NSLinkAttributeName, value: "changeNode", range: NSMakeRange(str.length-4, 4))

str.addAttribute(NSAttachmentAttributeName, value: NSColor.red, range: NSMakeRange(str.length-4, 4))

self.contentLabel.attributedStringValue = str


实现MyTextField的delegate方法:

extension ViewController: MyTextFieldDelegate {

func changeNodeClicked() {

self.changeNodeFunc() //自定义的点击后函数调用

}

}

你可能感兴趣的:(Mac OSX - 资料)