如何在悬停NSTextView上更改光标?雨燕4,Xcode 9.4

时间:2018-09-18 00:51:22

标签: swift macos nstextview nscursor

我有一个简单的NSTextView,它看起来像一个超链接,当用户将鼠标悬停在此NSTextView上时,我想更改指针上的光标。我该怎么做?我了解NSCursor,但是苹果文档很烂,没有示例,我无法使用它。

这是我的NSTextView

let linkView = NSTextView()
    linkView.font = NSFont(name: "SF Pro Display", size: 13)
    linkView.isEditable = false
    linkView.isFieldEditor = false
    linkView.isHidden = false

    linkView.string = (URL(string: (data?.link)!)?.host)!

    let attributedString = NSMutableAttributedString(string: linkView.string)
    let range = NSRange(location: 0, length: linkView.string.count)
    let url = URL(string: (data?.link)!)

    attributedString.setAttributes([.link: url!], range: range)
    linkView.textStorage?.setAttributedString(attributedString)

    linkView.linkTextAttributes = [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]

2 个答案:

答案 0 :(得分:0)

将光标样式添加到链接文本属性:

link.linkTextAttributes = [.cursor: NSCursor.pointingHand]

答案 1 :(得分:0)

尝试一下,它对我有用:

import Cocoa

class HyperlinkTextView: NSTextView {

    private(set) var href: String = ""

    //MARK: Override

    override func updateTrackingAreas() {
        for area in self.trackingAreas {
            self.removeTrackingArea(area)
        }
        self.addTrackingRect(self.bounds, owner: self, userData: nil, assumeInside:     false)
    }

    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        if let url = URL(string: self.href) {
            NSWorkspace.shared.open(url)
        }
    }

    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        //Added a pointing hand here
        self.addCursorRect(self.bounds, cursor: .pointingHand)
    }

    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        //Back to the system cursor
        self.removeCursorRect(self.bounds, cursor: .pointingHand)
    }

    //MARK: Public

    func setHref(name: String, link: String) {

        self.href = link

        let attrTitle = NSMutableAttributedString.init(string: name)
        let range = NSMakeRange(0, attrTitle.length)
        attrTitle.addAttributes([NSAttributedString.Key.link : NSURL.init(string: link)!], range: range)
        attrTitle.setAlignment(NSTextAlignment.center, range: range)
        self.linkTextAttributes = [
            .font: NSFont.systemFont(ofSize: 10.0),
            .foregroundColor: NSColor.blue,
            .underlineStyle: NSUnderlineStyle.single.rawValue,
        ]
        self.textStorage?.setAttributedString(attrTitle)

    }

}