如何用可点击的第一个单词创buildUILabel

我想在iOS中创build标签,任何人都可以帮助我将标签文本的第一个字加粗并可点击。 标签显示用户名及其评论,第一个词总是用户名。 提前致谢!

我想更优雅的解决scheme将使用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; } 

关键:

 ... 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); } 

完整的源代码

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

希望能帮助到你。

BR。
尤金

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

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

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

 NSArray* wordArray = [yourLabel.text componentsSeparatedByString: @" "]; NSString* firstWord = [wordArray objectAtIndex: 0]; 
  • 制作一个自定义的button,其中将包含您的用户名的第一个字,使文本加粗。
  • 拿一个标签,就在自定义button旁边,写下除第一个单词以外的其他用户名。
  • 在自定义button的点击事件上,做任何你想做的事情。

希望这个对你很清楚。

享受编程!

标签似乎很难。 Ypu可以使用一个视图。 添加一个button,并排标签,并添加第一个字符button和其他标签。

你需要添加一个UIGestureRecognizer到你的UILabel

 [myLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelActionPerformed)]]; 

//然后你可以有你的方法

 -(void)myLabelActionPerformed { NSLog(@"I tapped a UILabel"); } 

记住要启用你的UILabel用户中断