首页 > 解决方案 > 如何使编程 UITableView 文本的一部分可点击?

问题描述

我有一个程序化的 UITableView。我想让其中一个字符串中的部分文本可点击。这可能吗?

var moreSectionItems = [(image:String, title:String, subtitle:String)]()
moreSectionItems.append((image: "clouds", title: "Clouds", subtitle: "See the beautiful CLOUDS"))
moreSectionItems.append((image: "Stars", title: "Stars", subtitle: "See the beautiful STARS")) 
sections.append((sectionTitle:"This is what you can see",sectionSubtitle: "See all the good things.",items:moreSectionItems))

特别是,我想让字幕中“云”和“星星”的部分加下划线和可点击。是否有可能做到这一点?因为我需要一个属性字符串,但 tableview 需要一个常规字符串。

标签: iosswiftuitableview

解决方案


您可以使用 label.attributtedTextNSLinkAttributeName

https://www.hackingwithswift.com/example-code/system/how-to-make-tappable-links-in-nsattributedstring

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
        attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL, options: [:])
        return false
    }
}

推荐阅读