首先,我们在开发的过程中,会遇到这样的问题。比如:点击某一部分的文字跳转到另一界面。无论是登录协议,保险协议等等吧。
点击用户协议——》跳转协议界面
但是UITextView提供了添加超连接的方法,ios7.0之后使用。或许你可以使用UILabel属性字符串和UIButton来实现,当然是想的方法多种。我就不在介绍了^_^
我来介绍一下UITextView的使用方法:
/*
* * @author wumeng, 16-06-29 17:06:25
* * @brief 创建textView
*/
-(void)createTextView{
//字符串的处理
NSString *str =@"@百度是大坏蛋@www.baidu.com";
NSString *matchStr = @"百度";
NSMutableAttributedString *MAttributedString = [[NSMutableAttributedString alloc]initWithString:str];
if ([str rangeOfString:matchStr].location!=NSNotFound) { /** *注意这个url必须是*****://***的格式不然url取不到字符串 */
[MAttributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"username://"] range:[[MAttributedString string] rangeOfString:matchStr]]; }
//UITextView的创建
UITextView *TV = [[UITextView alloc]initWithFrame:CGRectMake(0, 60, 300, 200)]; TV.backgroundColor = [UIColor grayColor];
//必须设为NO不然不能响应点击事件
TV.editable = NO;
//设置点击时的样式
NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: [UIColor greenColor],NSUnderlineColorAttributeName: [UIColor lightGrayColor],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)};
//添加链接文字
/** 设置自动检测类型为链接网址. */
TV.dataDetectorTypes = UIDataDetectorTypeLink; TV.delegate = self;
TV.attributedText = MAttributedString;
[self.view addSubview:TV];
}
#pragma mark - textViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
NSLog(@"%@",[URL scheme]);
if ([[URL scheme] containsString:@"username"]) { NSLog(@"点中了。。。。。。。。");
}
return YES;//跳转到浏览器
}
不过你们可以把它封装成一个类来使用,不过也有几个需要注意的点
添加属性链接的URL需要注意的地方,必须使用xxxx://xxxx的格式。
/* 注意这个url必须是://**的格式不然url取不到字符串 */
[MAttributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"username://"] range:[[MAttributedString string] rangeOfString:matchStr]];
在代理方法回调的时候,如果没有“://”的话,在[URL scheme]方法里取不到特定的值,一句话://前面的才是最重要的标识符
原文链接:
(http://www.th7.cn/Program/IOS/201606/889796.shtml)