iOS 文字可点击响应Label - swift 版

2018-08-24  本文已影响292人  qui丶MyLove
demo GitHub

原理

UITextView 设置attributedText,attributedText中可以添加点击链接,点击执行回调。在一个view中添加两个一样的textView,上面textView的关闭响应isUserInteractionEnabled,下面的textview关闭isEditable。将两个textview添加到view上添加约束大小和view一样。

 /// 点击响应部分字符串
    private var clickStr:String? {
        didSet{
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineBreakMode = NSLineBreakMode.byCharWrapping
            
            keyRange = content!.range(of: clickStr!)
            let att:NSMutableAttributedString = NSMutableAttributedString(string: content!)
            att.addAttribute(NSAttributedStringKey.link, value: URL(string: clickKey)!, range: "".nsRange(from: keyRange!))
            att.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: textFont), range: NSMakeRange(0, content!.count))
            att.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, content!.count))
            self.contentView.attributedText = att
            
            let att1:NSMutableAttributedString = NSMutableAttributedString(string: content!)
            att1.addAttribute(NSAttributedStringKey.foregroundColor, value: keyColor!, range: "".nsRange(from: keyRange!))
            att1.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: textFont), range:NSMakeRange(0, content!.count))
            att1.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, content!.count))
            self.subContentView.attributedText = att1
        }
    }
//点击textview中的url 回调
 func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        
        if URL.absoluteString == clickKey {
            if let tmp = clickBlock {
                tmp(clickStr)
            }
        }
        return false
    }

上一篇下一篇

猜你喜欢

热点阅读