【发布时间】:2014-07-01 09:15:11
【问题描述】:
我正在尝试在UITextView 中找到 Tapped String。我试过UIDataDetectorTypeLink.但它不起作用。我也不确定是否可以检测到String。我在自定义UITableViewCell 中使用UITextView。从那我试图检测轻敲的字符串。下面也是我尝试过的示例代码。谁能帮我找出我做错了什么,我该如何解决?
即使不可能,我该如何解决这个问题?
NSMutableArray *sampleArray = [[NSMutableArray alloc]init];
NSMutableString *mutableString = [[NSMutableString alloc]init];
NSMutableAttributedString * string;
sampleArray = [[postArray valueForKey:@"hash_tags"] objectAtIndex:indexPath.row];
for(NSString *sampleString in sampleArray){
if (mutableString.length == 0) {
[mutableString appendString:sampleString];
}else{
[mutableString appendString:[NSString stringWithFormat:@", %@",sampleString]];
}
string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",mutableString]];
// [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,[string length])];
}
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:5.0f/255.0f green:107.0f/255.0f blue:153.0f/255.0f alpha:1.0f], NSUnderlineColorAttributeName: [UIColor greenColor],NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
[string addAttribute:NSLinkAttributeName
value:string
range:NSMakeRange(0, [string length])];//[[string string] rangeOfString:sampleString]];
[cell.tagsTextView setAttributedText:string];
[cell.tagsTextView setDelegate:self];
[cell.tagsTextView setUserInteractionEnabled:YES];
cell.tagsTextView.scrollEnabled = NO;
cell.tagsTextView.editable = NO;
cell.tagsTextView.dataDetectorTypes = UIDataDetectorTypeLink;
// cell.tagsTextView.textContainer.lineFragmentPadding = 0;
// cell.tagsTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
[cell.tagsTextView setLinkTextAttributes:linkAttributes];
UITextView Delegates
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
NSLog(@"url %@",URL);
if ([[URL scheme] isEqualToString:@"username"]) {
NSString *username = [URL host];
// do something with this username
// ...
return NO;
}
return YES; // let the system open this URL
}
提前致谢
【问题讨论】:
-
添加一个 TapGesture 识别器,禁用
UITextView的可编辑属性(您似乎已经这样做了),并使用UITextPosition和UITextView查找问题。还是只查找带有链接的NSAttributedString? -
你所说的“Tapped String”是什么意思?你在找一个词吗?一行文字?某个子串?
-
例如:如果
UITextView中的字符串类似于@John、@David、@Larme,那么如果用户点击字符串@John然后我需要检测到用户已经从UITextView中点击了 @John 字符串。我怎样才能实现这个字符串检测? -
@Larme - 谢谢Larme,我已经使用了TapGesture 并检测到了轻敲的字符串。它正在工作,我已经在下面回答了。
标签: ios objective-c uitableview nsstring uitextview