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() //自定义的点击后函数调用

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、改变 UITextField 占位文字 颜色和去掉底部白框 [_userName setValue:[UICo...
    i_MT阅读 4,709评论 0 2
  • 1、设置UILabel行间距 NSMutableAttributedString* attrString = [[...
    FF_911阅读 5,272评论 0 3
  • 1-7条 //Objective-C消息型语言,运行时所应该执行的代码室友运行期环境来决定的,使用函数调用的语言则...
    静候花开_ycb阅读 1,670评论 0 0
  • 最佳配角策略 1.选择合适的话题 2.进行合适的提问 3.根据话题归纳出对方的优点,进行恭维。 选择合适的话题 不...
    鹿伟伦阅读 2,187评论 0 0
  • 彷徨得太久,想把自己锁住 加了把锁,钥匙却忘在了外面 打不开,出不去 心,独自飞向蓝天 蓝天不常有,心也迷了路 我...
    简姝k阅读 1,715评论 3 2

友情链接更多精彩内容