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

时间:2015-12-29 14:58:04

标签: ios swift uilabel nsattributedstring

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

3 个答案:

答案 0 :(得分: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);    
}

答案 1 :(得分:1)

**ClickableTextView.h**

@protocol ClickableTextViewDelegate <NSObject>

@required
-(void)textview:(UITextView *)clickableTextView clickedText:(NSString *)text;

@end

@interface ClickableTextView : UITextView

@property (weak, nonatomic) id <ClickableTextViewDelegate> tapDelegate;

-(instancetype)initWithDelegate:(id)delegate;

@end


**ClickableTextView.m**

-(void)awakeFromNib {
    [super awakeFromNib];

    [self setProperties];
}


-(void)setProperties {

  self.userInteractionEnabled = YES;
  self.editable = NO;
  self.scrollEnabled = NO;
  self.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
  self.dataDetectorTypes = UIDataDetectorTypeLink;
  self.backgroundColor = [UIColor clearColor];

  /* Set Tap gesture on Text view */
  UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapResponse:)];
  tapGesture.numberOfTapsRequired = 1;
  [self 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); 

if(tappedWord) {

    if([self.tapDelegate respondsToSelector:@selector(textview:clickedText:)]){
        [self.tapDelegate textview:self clickedText:tappedWord];
    }
 }

}

在TableViewCell中使用此自定义类而不是UITextView,然后在

中设置委托
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

并在委托方法中获得结果。

-(void)textview:(UITextView *)clickableTextView clickedText:(NSString *)text {
}

答案 2 :(得分:-2)

Swift 2.0:

最好使用UITextView。

1)制作TapGesture并添加到UITextView。     override func viewDidLoad(){         super.viewDidLoad()

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapResponse:")
    tapGesture.numberOfTapsRequired = 1
    sampleTextView.addGestureRecognizer(tapGesture)    
}

2)添加获取所选单词的方法。

func tapResponse(recognizer: UITapGestureRecognizer) {
        let location: CGPoint = recognizer.locationInView(sampleTextView)
        let position: CGPoint = CGPointMake(location.x, location.y)
        let tapPosition: UITextPosition = sampleTextView.closestPositionToPoint(position)!
        let textRange: UITextRange = sampleTextView.tokenizer.rangeEnclosingPosition(tapPosition, withGranularity: .Word, inDirection: 1)!

        let tappedWord: String = sampleTextView.textInRange(textRange)!
        print("tapped word : %@", tappedWord)
    }