TTTAttributedLabel链接检测在iOS8中使用swift无法正常工作

Jer*_*Wei 8 uitableview ios tttattributedlabel swift ios8

我想使用TTTAttributedLabel来检测UITableViewCell标签中文本的链接,但它不起作用.我正在使用iOS8的swift.下面是UITableViewCell代码:

class StoryTableViewCell: UITableViewCell, TTTAttributedLabelDelegate {
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        // Link properties
        let textLabel = self.descriptionLabel
        let linkColor = UIColor(red: 0.203, green: 0.329, blue: 0.835, alpha: 1)
        let linkActiveColor = UIColor.blackColor()

        if (textLabel is TTTAttributedLabel) {
            var label = textLabel as TTTAttributedLabel
            label.linkAttributes = [NSForegroundColorAttributeName : linkColor]
            label.activeLinkAttributes = [NSForegroundColorAttributeName : linkActiveColor]        
            label.enabledTextCheckingTypes = NSTextCheckingType.Link.toRaw()

            label.delegate = self
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

E-R*_*die 12

我认为你还没有custom cell 正确配置.

首先在customCell上声明并连接你的IBOutlet-s.选择textLabel并将其类添加到TTTAttributedLabel.您的自定义单元格应如下所示:

class StoryTableViewCell: UITableViewCell {
    @IBOutlet weak var textLabel: TTTAttributedLabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
Run Code Online (Sandbox Code Playgroud)

其次,您需要TTTAttributedLabelDelegate在使用tableView数据源和委托的类中添加.

然后cellForRowAtIndexPath

var cell: StoryTableViewCell = tableView.dequeueReusableCellWithIdentifier("yourCellIdentifier") as StoryTableViewCell

let linkColor = UIColor(red: 0.203, green: 0.329, blue: 0.835, alpha: 1)
let linkActiveColor = UIColor.blackColor()

cell.textLabel.delegate = self

cell.textLabel.linkAttributes = [kCTForegroundColorAttributeName : linkColor]
cell.textLabel.activeLinkAttributes = [kCTForegroundColorAttributeName : linkActiveColor]        
cell.textLabel.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
Run Code Online (Sandbox Code Playgroud)

然后,如果您有需要执行的方法,请TTTAttributedLabelDelegate添加它们并进行计算.

希望能帮助到你

  • 似乎NSForegroundColorAttributeName不能在iOS8上运行.如果发生这种情况,请改用kCTForegroundColorAttributeName. (5认同)