gpt4 book ai didi

ios - 如何使 UILabel 中的特定单词可选(Swift 2.0)?

转载 作者:行者123 更新时间:2023-11-28 09:37:04 25 4
gpt4 key购买 nike

我一整天都在面对一个可能有一个简单解决方案的大问题。我有一个 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))

最佳答案

您可以使用 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);
}

关于ios - 如何使 UILabel 中的特定单词可选(Swift 2.0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com