如何使用可点击的第一个单词创建UILabel

SAM*_*HOD 7 iphone objective-c uilabel ipad ios

我想在iOS中创建标签,任何人都可以帮助我使标签文本的第一个单词加粗和可点击.标签显示用户名及其注释,第一个单词始终是用户名.提前致谢!

dym*_*ymv 10

我想更优雅的解决方案是使用TTTAttributedString或类似的.

例:

简单的演示

输出:

2013-03-10 07:16:54.429 ClickableUILabel-SO[4770:c07] UserName clicked
Address:    {
    comment = "Your comment.";
    userName = user2126537;
}
2013-03-10 07:16:55.460 ClickableUILabel-SO[4770:c07] UserName clicked
Address:    {
    comment = "Another comment.";
    userName = nsgulliver;
}
Run Code Online (Sandbox Code Playgroud)

关键点:

...

NSRange userNameRange = [text rangeOfString: userName];

...

label.delegate = self;
[label addLinkToAddress: @{
           @"userName" : userName,
            @"comment" : comment
    }
                  withRange: userNameRange];

...

- (void) attributedLabel: (TTTAttributedLabel *)label
didSelectLinkWithAddress: (NSDictionary *)addressComponents
{
    NSLog(@"UserName clicked\nAddress:\t%@", addressComponents);
}
Run Code Online (Sandbox Code Playgroud)

完整的源代码

请注意,您应该xcworkspace在Xcode/AppCode中打开,因为我在这里使用CocoaPods.

希望能帮助到你.

BR.
尤金


nsg*_*ver 4

您需要用于UITapGestureRecognizer 使UILabel可点击。使用UIView 并添加UILabel为子视图

UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourMethod:)];
[yourLabelView setUserInteractionEnabled:YES];
[yourLabelView addGestureRecognizer:gesture];
Run Code Online (Sandbox Code Playgroud)

制作第一个单词的一种方法clickable是使用 string 方法从标签中取出第一个单词并将其存储在另一个标签中,然后使用上面的代码使其可点击

NSArray* wordArray = [yourLabel.text componentsSeparatedByString: @" "];
NSString* firstWord = [wordArray objectAtIndex: 0];
Run Code Online (Sandbox Code Playgroud)