【问题标题】:Tap action on some part of attributed string in iOS在 iOS 中对属性字符串的某些部分进行点击操作
【发布时间】:2015-06-12 09:21:45
【问题描述】:

我想对 UILabel 部分进行点击操作。 例如:如果我们有像“我的名字是 XYZ”这样的字符串,在这种情况下,我只想为“XYZ”添加点击动作。

如何在 iOS 中做到这一点(swift)

【问题讨论】:

    标签: ios iphone nsattributedstring


    【解决方案1】:

    在 Objective-C 中有一个控制调用 TTTAttributedLabel 可以处理同样的事情,所以你可以使用它,

    TTTAttributedLabel *tttLabel = <# create the label here #>;
    NSString *labelText = @"Lost? Learn more.";
    tttLabel.text = labelText;
    NSRange r = [labelText rangeOfString:@"Learn more"];
    [tttLabel addLinkToURL:[NSURL URLWithString:@"action://show-help"] withRange:r];
    

    然后,在您的 TTTAttributedLabelDelegate 中:

    - (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    if ([[url scheme] hasPrefix:@"action"]) {
        if ([[url host] hasPrefix:@"show-help"]) {
            /* load help screen */
        } else if ([[url host] hasPrefix:@"show-settings"]) {
            /* load settings screen */
        }
    } else {
        /* deal with http links here */
    }}
    

    对于 Swift,你可以做一些类似的事情,

    let name = "tomo"
    let string = "My name is \(name)"
    label.text = string
    let nsString = string as NSString
    let range = nsString.rangeOfString(name)
    let url = NSURL(string: "action://users/\(name)")!
    label.addLinkToURL(url, withRange: range)
    

    【讨论】:

    • 感谢您的快速回复。我们可以在 swift 中使用 NSAttributedString 来做到这一点吗?。
    【解决方案2】:

    如何在 UIButton 旁边的 UIView 中设置标签?

    UIView *view = [UIView new];
    UILabel *label = [UILabel new];
    UIButton *button = [UIButton new];
    

    将这些约束添加到视图中:

    |[label][button]|
    
    label.text = @"My name is"
    [button setTitle:yourName forState:UIControlStateNormal];
    

    通过将标签和按钮的背景颜色设置为 clearColor 并将视图的背景背景设置为 whiteColor(例如),您应该不会看到太大的差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-16
      • 2012-02-18
      • 1970-01-01
      • 2017-06-19
      • 2012-11-17
      • 1970-01-01
      • 2016-01-12
      • 2014-09-07
      相关资源
      最近更新 更多