TTTAttributedLabel链接正在设置样式但不可点击

Mat*_*ers 7 hyperlink ios tttattributedlabel swift

我一直在研究获得可点击链接的解决方案.我可以在使用UITextView + NSAttributedString时使用它,但当它是UITableViewCell时它不会正确地自动布局.

现在我已经将TTTAttributedLabel添加到我的项目中,它完美地调整了视图的样式.链接也变为蓝色并加下划线.

但是点击它们什么都不做.我确实在我的控制器上实现了TTTAttributedLabelDelegate,在故事板中实现了标签实现MyLabel(它只是扩展了TTTAttributedLabel并具有委托选项,因为我希望它们在同一个函数中触发).现在我已经将控制器设置为我认为可能无法指向自身的委托.

但这些功能都没有被解雇,我得到了断点并登录了它.

我实现了didSelectLinkWithUrl和didLongPressLinkWithUrl.

 func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
        Debug.log("link clicked")
    }
    func attributedLabel(label: TTTAttributedLabel!, didLongPressLinkWithURL url: NSURL!, atPoint point: CGPoint) {
        Debug.log("link long clicked")
    }
Run Code Online (Sandbox Code Playgroud)

出口

@IBOutlet weak var content: MyLabel!
Run Code Online (Sandbox Code Playgroud)

MyLabel

导入UIKit导入TTTAttributedLabel

class MyLabel : TTTAttributedLabel, TTTAttributedLabelDelegate {

override func didMoveToSuperview() {
    if (self.delegate == nil) {
        self.delegate = self
    }
    self.enabledTextCheckingTypes = NSTextCheckingType.Link.rawValue
    self.userInteractionEnabled = true
}

func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
    Debug.log("link clicked")
}
func attributedLabel(label: TTTAttributedLabel!, didLongPressLinkWithURL url: NSURL!, atPoint point: CGPoint) {
    Debug.log("link long clicked")
}
Run Code Online (Sandbox Code Playgroud)

谁知道我可能会失踪?

更新

我发现只是粘贴在一个url f/e http://example.com变得活跃并且实际上是可点击的并且didSelectLinkWithUrl变得可点击,尽管我需要一个属性字符串并且它基于HTML字符串.

Aar*_*ger 13

执行时setAttributedText:不会更新linkModels数组,而执行setText:的确如此.我相信这是导致你的问题的原因.

要解决此问题,请设置标签的text属性而不是attributedText属性.

文档还包括此警告:

TTTAttributedLabel可以显示普通文本和属性文本:只需传递一个NSString或者NSAttributedString到一个setText:setter.永远不要分配给attributedText酒店.

文档还显示了此示例用法:

TTTAttributedLabel *attributedLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:@"Tom Bombadil"
                                                                attributes:@{
        (id)kCTForegroundColorAttributeName : (id)[UIColor redColor].CGColor,
        NSFontAttributeName : [UIFont boldSystemFontOfSize:16],
        NSKernAttributeName : [NSNull null],
        (id)kTTTBackgroundFillColorAttributeName : (id)[UIColor greenColor].CGColor
}];

// The attributed string is directly set, without inheriting any other text
// properties of the label.
attributedLabel.text = attString;
Run Code Online (Sandbox Code Playgroud)