如何在 Swift iOS 中一起使用 UITableView 和 NSLink?

亚当

扩展代码:

extension String {    
func accentTagAndLink(tags:Array<String>) -> NSMutableAttributedString {

    let attributedString:NSMutableAttributedString = NSMutableAttributedString(string: self)
    var NSContents = self as NSString

    for tagChild in tags {
        if !tagChild.starts(with: "<") {
            let range = NSContents.range(of: "#" + tagChild)
            var changeString = ""

            for _ in 0..<tagChild.count {
                changeString += "$"
            }

            NSContents = NSContents.replacingOccurrences(of: tagChild, with: changeString, options: .literal, range: range) as NSString
            attributedString.addAttribute(.link, value: tagChild, range: range)
            attributedString.addAttribute(.foregroundColor, value: UIColor(red: 79/255, green: 205/255, blue: 255/255, alpha: 1), range: range)
        }
    }

    return attributedString
}
}

表视图单元格:

class PostCell: TableViewCell {
    @IBOutlet weak var postContent: UITextView!
}

在主视图控制器中

class PostViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UITextViewDelegate {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = postTableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
        let post = postList[indexPath.row]
        let tags = (post["Content"] as! String).FindTagAtString()
        cell.postContent.delegate = self
        cell.postContent.isSelectable = true
        cell.postContent.isEditable = false
        cell.postContent.isUserInteractionEnabled = true
        cell.postContent.dataDetectorTypes = UIDataDetectorTypes.link
        cell.postContent.attributedText = (post["Content"] as! String).accentTagAndLink(tags: tags)
        let tap = MyTapGesture(target: self, action: #selector(self.tapTextView))
            tap.indexPath = indexPath
        cell.postContent.addGestureRecognizer(tap)
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(URL)
        return true
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("cell tap")
        movePostDetail(indexPath)
    }
    @objc func tapTextView(sender:MyTapGesture){
        print("cell tap")
        movePostDetail(sender.indexPath)

    }
}

我的点击手势:

class MyTapGesture: UITapGestureRecognizer {
    var indexPath:IndexPath!
}

内容是 NormalText + TagText

如果点击 NormalText 运行 movePostDetail 并且如果点击 TagText 运行 print(URL) 但总是 movePostDetail 时 addGestureRecognizer

一起使用方法

我拿的时候效果很好TTTAttributedLabel,但因为崩溃所以我没用过TTTAttributedLabel

土豆

我建议您使用自定义属性名称并自己处理水龙头。

Swift 4 中的解决方案

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    let tapGes = UITapGestureRecognizer(target: self, action: #selector(TableViewCell.handleTap(sender:)))
    contentTf.addGestureRecognizer(tapGes)

    let attributeName = "CustomAttributeName"
    let attStr = NSAttributedString(string: "https", attributes: [NSAttributedStringKey(rawValue: attributeName):"https"])

    contentTf.attributedText = attStr
}
@objc func handleTap(sender: UITapGestureRecognizer) -> Void {
    let myTextView = sender.view as! UITextView
    let layoutManager = myTextView.layoutManager

    // location of tap in myTextView coordinates and taking the inset into account
    var location = sender.location(in: myTextView)
    location.x -= myTextView.textContainerInset.left;
    location.y -= myTextView.textContainerInset.top;

    // character index at tap location
    let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

    // if index is valid then do something.
    if characterIndex < myTextView.textStorage.length {

        // print the character index
        print("character index: \(characterIndex)")

        // print the character at the index
        let myRange = NSRange(location: characterIndex, length: 1)
        let substring = (myTextView.attributedText.string as NSString).substring(with: myRange)
        print("character at index: \(substring)")

        // check if the tap location has a certain attribute
        let attributeName = "CustomAttributeName"
        let attributeValue = myTextView.attributedText.attribute(NSAttributedStringKey(rawValue: attributeName), at: characterIndex, effectiveRange: nil) as? String
        if let value = attributeValue {
            print("You tapped on \(attributeName) and the value is: \(value)")
        }

    }
}

测试

character index: 3
character at index: p
You tapped on CustomAttributeName and the value is: https

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在while和foreach循环中一起使用PHP和MySQL?

如何在PHP中一起使用复选框和输入类型编号

如何在SQL Server中一起使用相等和不相等

如何在for循环中一起使用innerHTML和ejs?

如何在 MongoDB 中一起使用 match 和 sum?

如何在Verilog中一起使用inout和reg

如何在python中一起使用.join()和.format()

如何在熊猫中一起使用distinct和where子句?

我如何在React中一起使用'update'和setState(prevState)?

如何在Google表格中一起使用to_date和IFERROR?

如何在 Pandas 中一起使用 groupby、select、count(*) 和 SQL 的 where 命令

如何在Bash中一起使用watch和jobs命令?

如何在Apache Beam中一起使用MapElements和KV?

如何在输入中一起使用 :value 和 v-model

如何在Python中一起使用filter,group by和agg函数

如何在SQL Server中一起使用count,case和Distinct

如何在laravel中一起使用whereBetween和like运算符?

如何在SQL中一起使用IN子句和AND子句

如何在Scrapy中一起使用http和https代理?

您如何在Groovy中一起使用GroupBy和Sum?

如何在SQL Server查询中一起使用LIKE和NOT LIKE

如何在angular 1中一起使用ng-if和ng-options

如何在SQL中一起使用数据透视和分组依据?

如何在Redis中一起使用复制和分片?

如何在适配器类和活动中一起使用Interface

如何在Powerapps中一起使用collect和if函数?

如何在Ansible中一起使用loop和with_nested

如何在Access VBA编码中一起使用Select Case和AND功能?

如何在SQLAlchemy中一起使用JOIN和SELECT AS?