【问题标题】:Simple clickable link in Cocoa and SwiftCocoa 和 Swift 中的简单可点击链接
【发布时间】:2016-07-12 23:16:19
【问题描述】:

我正在为 mac 10.11 快速编写一个桌面应用程序,我想添加一个指向 about 页面的链接。

很像这样:https://developer.apple.com/library/mac/qa/qa1487/_index.html

我找不到好的教程或参考资料。

任何帮助将不胜感激

【问题讨论】:

    标签: swift cocoa hyperlink


    【解决方案1】:

    Swift 4,xCode 9

    @IBDesignable
    class HyperlinkTextField: NSTextField {
    
        @IBInspectable var href: String = ""
    
        override func resetCursorRects() {
            discardCursorRects()
            addCursorRect(self.bounds, cursor: NSCursor.pointingHand)
        }
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
            // TODO:  Fix this and get the hover click to work.
    
            let attributes: [NSAttributedStringKey: Any] = [
                NSAttributedStringKey.foregroundColor: NSColor.linkColor,
                NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue as AnyObject
            ]
            attributedStringValue = NSAttributedString(string: self.stringValue, attributes: attributes)
        }
    
        override func mouseDown(with theEvent: NSEvent) {
            if let localHref = URL(string: href) {
                NSWorkspace.shared.open(localHref)
            }
        }
    }
    

    【讨论】:

    • 将 NSColor.blue 更改为 NSColor.linkColor 以便在 10.14 中获得更好的支持
    • 如果NSAttributedStringKey 没有出现在建议中使用NSAttributedString.KeyNSAttributedStringKey.foregroundColor 使用NSAttributedString.Key.foregroundColor
    【解决方案2】:

    修改了现有答案以允许标签文本的子字符串变为下划线和蓝色,因此您可以执行以下操作:This 是答案

    // A text field that can contain a hyperlink within a range of characters in the text.
    @IBDesignable
    public class SubstringLinkedTextField: NSTextField {
        // the URL that will be opened when the link is clicked.
        public var link: String = ""
        @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'link' instead.")
        @IBInspectable public var HREF: String {
            get {
                return self.link
            }
            set {
                self.link = newValue
                self.needsDisplay = true
            }
        }
    
        // the substring within the field's text that will become an underlined link. if empty or no match found, the entire text will become the link.
        public var linkText: String = ""
        @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'linkText' instead.")
        @IBInspectable public var LinkText: String {
            get {
                return self.linkText
            }
            set {
                self.linkText = newValue
                self.needsDisplay = true
            }
        }
    
        override public func awakeFromNib() {
            super.awakeFromNib()
    
            self.allowsEditingTextAttributes = true
            self.isSelectable = true
    
            let url = URL(string: self.link)
            let attributes: [NSAttributedStringKey: AnyObject] = [
                NSAttributedStringKey(rawValue: NSAttributedStringKey.link.rawValue): url as AnyObject
            ]
            let attributedStr = NSMutableAttributedString(string: self.stringValue)
    
            if self.linkText.count > 0 {
                if let range = self.stringValue.indexOf(substring: self.linkText) {
                    attributedStr.setAttributes(attributes, range: range)
                } else {
                    attributedStr.setAttributes(attributes, range: NSMakeRange(0, self.stringValue.count))
                }
            } else {
                attributedStr.setAttributes(attributes, range: NSMakeRange(0, self.stringValue.count))
            }
            self.attributedStringValue = attributedStr
        }
    }
    

    【讨论】:

      【解决方案3】:

      最简单的方法是继承NSTextField 以创建HyperlinkTextField。下面是一个例子:

      首先,让我们在您的项目中添加一个HyperlinkTextField 类:

      // HyperlinkTextField.swift
      
      import Cocoa
      
      @IBDesignable
      class HyperlinkTextField: NSTextField {
          @IBInspectable var href: String = ""
      
          override func awakeFromNib() {
              super.awakeFromNib()
      
              let attributes: [String: AnyObject] = [
                  NSForegroundColorAttributeName: NSColor.blueColor(),
                  NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue
              ]
              self.attributedStringValue = NSAttributedString(string: self.stringValue, attributes: attributes)
          }
      
          override func mouseDown(theEvent: NSEvent) {
              NSWorkspace.sharedWorkspace().openURL(NSURL(string: self.href)!)
          }
      }
      

      接下来,在 Interface Builder 中,将标签从对象库拖到您的窗口中。

      选择该标签,进入菜单View > Utilities > Show Identity Inspector(或按Cmd + Opt + 3)并将类更改为HyperlinkTextField

      转到 Attributes Inspector (Cmd + Opt + 4) 并将 Href 设置为您要访问的 URL。

      标签在 Interface Builder 中显示黑色文本,但当您运行应用程序时一切都会好起来的。点击标签将在您的默认浏览器中打开链接。

      我无法实现的一件事是让 HyperlinkTextField 在 Interface Builder 中显示为蓝色并带有下划线。欢迎就如何做到这一点发表评论。

      【讨论】:

        【解决方案4】:

        正是我需要的。这是Swift3 版本:

        import Cocoa
        
        @IBDesignable
        class HyperTextField: NSTextField {
            @IBInspectable var href: String = ""
        
            override func awakeFromNib() {
                super.awakeFromNib()
        
                let attributes: [String: AnyObject] = [
                    NSForegroundColorAttributeName: NSColor.blue,
                    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue as AnyObject
                ]
                self.attributedStringValue = NSAttributedString(string: self.stringValue, attributes: attributes)
            }
        
            override func mouseDown(with event: NSEvent) {
                NSWorkspace.shared().open(URL(string: self.href)!)
            }
        }
        

        【讨论】:

          【解决方案5】:
          let link = NSTextField()
          link.isBezeled = false
          link.drawsBackground = false
          link.isEditable = false
          link.isSelectable = true
          link.allowsEditingTextAttributes = true
          let url = URL(string: "http://www.google.com")
          let linkTextAttributes: [NSAttributedStringKey: Any] = [
                  NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
                  NSAttributedStringKey.foregroundColor: NSColor.blue,
                  NSAttributedStringKey.link: url as Any
                      ]
          let string = "whatever"
          link.attributedStringValue = NSAttributedString(string: string, attributes: linkTextAttributes)
          window.contentView?.addSubview(link)
          

          【讨论】:

            【解决方案6】:

            斯威夫特 4.2

            class HyperlinkTextField: NSTextField {
            
            
            private var detector: NSDataDetector!
            
            override func awakeFromNib() {
                super.awakeFromNib()
                 detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
            }
            
            
            func setText(text: String ){
                let matches = detector.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
            
                for match in matches {
                    guard let range = Range(match.range, in: text) else { continue }
                    let url = text[range]
                    let attributedString = NSMutableAttributedString(string: text)
                    attributedString.addAttribute(.link, value: url, range: match.range)
                    self.attributedStringValue = attributedString
                }
            }
            

            }

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-04-08
              • 1970-01-01
              • 2015-10-06
              • 2017-09-06
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多