如何在UILabel中选择特定单词(Swift 2.0)?

Ana*_*and 0 nsattributedstring uilabel ios swift

我一直面临一个大问题,可能整天都有一个简单的解决方案.我有一个UILabel,它包含一个NSAttributedString.我想要一个特定的范围UILabel来进行点播.我不想要任何第三方功能.

这是我的示例代码:

let str = dict["itemName"] as! NSString
range = string.rangeOfString(dict["itemName"] as! String)!
index = string.startIndex.distanceTo(range.startIndex)
attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: index, length: str.length))
Run Code Online (Sandbox Code Playgroud)

rus*_*ani 8

您可以使用UITextview并添加点按手势,而不是使用UILabel.这是一个例子,通过你可以实现相同的结果.

/* Set Tap gesture on Text view */

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapResponse:)];
tapGesture.numberOfTapsRequired = 1;
[yourTextView addGestureRecognizer:tapGesture];

- (void) tapResponse:(UITapGestureRecognizer *)recognizer
{

UITextView *textView =  (UITextView *)recognizer.view;
CGPoint location = [recognizer locationInView:textView];

CGPoint position = CGPointMake(location.x, location.y);

//get location in text from textposition at point
UITextPosition *tapPosition = [textView closestPositionToPoint:position];

//fetch the word at this position (or nil, if not available)
UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
NSString *tappedWord = [textView textInRange:textRange];

NSLog(@"tapped word : %@", tappedWord);    
}
Run Code Online (Sandbox Code Playgroud)