我在一个iOS应用程序,应该能够突出显示文本,并使其可点击.
我在iOS中阅读了约NSAttributedString,但是在android中比Spannable还要复杂.
有没有其他目标c的做法,如果没有;我应该如何使用NSAttributedString来逐句突出显示一个段落,以及如何使我的文本可点击.
更新:
What exactly i want that each word should be clickable and can be
highlighted as a single word in one paragraph.
解决方法
我发现使用UITextView的完美解决方案,它将使UITextView内的每个单词都可以点击.
首先,创建一个UITextView,然后添加一个UITapGestureRecognizer,如下所示:
CGRect textViewFrame = CGRectMake(0,40,100,100); textView = [[UITextView alloc]initWithFrame: textViewFrame]; textView.textAlignment = NSTextAlignmentCenter; textView.backgroundColor = [UIColor clearColor]; textView.editable = NO; textView.selectable = NO; [self.view addSubView:textView]; // i used to `NSMutableAttributedString` highlight the text string = [[NSMutableAttributedString alloc]initWithString:@"Any text to detect A B $& - +"]; [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:40.0] range:NSMakeRange(0,[string length])]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ; [paragraphStyle setAlignment:NSTextAlignmentCenter]; [string addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[string length])]; [textView setAttributedText:string]; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)]; //modify this number to recognizer number of tap [singleTap setNumberOfTapsrequired:1]; [textView addGestureRecognizer:singleTap];
然后添加UITapGestureRecognizer @selector:
- (void)tapRecognized:(UITapGestureRecognizer *)recognizer{ if(recognizer.state == UIGestureRecognizerStateRecognized) { CGPoint point = [recognizer locationInView:recognizer.view]; NSString * detectedText = [self getWordAtPosition:point inTextView: textView]; if (![detectedText isEqualToString:@""]) { NSLog(@"detectedText == %@",detectedText); } } }
所有这些魔法与这个方法有关,女巫可以检测到UITextView上的任何触摸,并获得点击的字:
-(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv { //eliminate scroll offset pos.y += _tv.contentOffset.y; //get location in text from textposition at point UITextPosition *tapPos = [_tv closestPositionToPoint:pos]; //fetch the word at this position (or nil,if not available) UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight]; return [_tv textInRange:wr]; }
-(void)setTextHighlited :(NSString *)txt{ for (NSString *word in [textView.attributedText componentsSeparatedByString:@" "]) { if ([word hasPrefix:txt]) { NSRange range=[self.textLabel.text rangeOfString:word]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range]; }} [textView setAttributedText:string]; }
就这样,希望这能帮助别人.