iOS富文本超链接和图片可点击

{

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.selectionStyle = .none
    self.contentView.addSubview(self.contentLab)
    contentLab.snp.makeConstraints { (make) in
        make.left.top.equalTo(kGetP(15))
        make.right.bottom.equalTo(-kGetP(15))
    }
}

var contentStr: String? {
    didSet {
        self.contentLab.attributedText = contentStr?.richTextToHtmlAttributedText()
        let height = self.contentLab.sizeThatFits(CGSize(width: kScreenWidth - kGetP(30) - self.contentLab.textContainer.lineFragmentPadding * 2, height: CGFloat(MAXFLOAT))).height
        self.contentLab.snp.remakeConstraints { (make) in
            make.left.top.equalTo(kGetP(15))
            make.height.equalTo(height)
            make.right.bottom.equalTo(-kGetP(15))
        }
    }
}

func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool {
    
    self.showBigPhoto(textAttachment: textAttachment)
    return true
}

@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    
    self.showBigPhoto(textAttachment: textAttachment)
    return true
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    //返回ture可以跳转到Safari浏览器,也可以返回false在这里进行自己的处理
    return false
}

func showBigPhoto(textAttachment: NSTextAttachment) -> Void {
    
    let image = UIImage.init(data: textAttachment.fileWrapper?.regularFileContents ?? Data())
     //此处获取到图片之后进行自己的处理
    let dataSource = JXLocalDataSource(numberOfItems: {
        // 共有多少项
        return 1
    }, localImage: { index -> UIImage? in
        // 每一项的图片对象
        return image
    })
    JXPhotoBrowser(dataSource: dataSource).show(pageIndex: 0)
}

lazy var contentLab: UITextView = {
    let tv = UITextView.init()
    tv.textColor = kSubTitleLabelColor
    tv.font = kFont(kPFFont_Regular, kGetP(14))
    tv.isSelectable = true
    tv.isEditable = false
    tv.isScrollEnabled = false
    tv.dataDetectorTypes = UIDataDetectorTypes.link
    tv.delegate = self
    return tv
}()

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

你可能感兴趣的:(iOS富文本超链接和图片可点击)