我有一个 UILabel ,其文本是www.google.com。现在,如果有人在文本上移动光标并按下它,谷歌的主页应该会打开。可能吗?请解释如何。
[emptyLabel setText:@"Sorry it looks like google is not currently available in any of your favourite places nearby, why not ask them to sign up at www.google.com"]
// While Loading the view
[self underlineLabel:label withFont:[UIFont systemFontOfSize:17]];
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myAction:)];
[label addGestureRecognizer:gr];
gr.numberOfTapsRequired = 1;
//
- (CGFloat)widthOfString:(NSString *)string withFont:(UIFont *)font {
CGSize stringSize = [string sizeWithFont:font];
CGFloat width = stringSize.width;
return width;
}
- (CGFloat)heightOfString:(NSString *)string withFont:(UIFont *)font {
CGSize stringSize = [string sizeWithFont:font];
CGFloat height = stringSize.height;
return height;
}
-(void)underlineLabel:(UILabel *)lbl withFont:(UIFont *)fnt {
float wdth = [self widthOfString:lbl.text withFont:fnt];
float higt = [self heightOfString:lbl.text withFont:fnt];
UIView *viw = [[UIView alloc]initWithFrame:CGRectMake((lbl.frame.size.width - wdth) / 2, (lbl.frame.size.height / 2) + (higt / 2), wdth, 2)];
[viw setBackgroundColor:[UIColor bluecolor]];
[lbl addSubview:viw];
}
// To Add action for gesture recognizer:
- (void)myAction:(UITapGestureRecognizer *)gr {
// Define actions here
}
您还可以使用 UITextView 并启用数据检测器并禁用编辑,这给人一种 UILabel 的感觉。设置了必要属性的 UItextview 会自动检测 http 链接、电话号码等
如果必须使用 UILabel,那么您需要添加一个 UITapgesture 并为点击提供一个目标。
考虑NIAttributedLabel
从Nimbus 项目中使用。这是一个UILabel
自动检测并创建可点击链接的插入式替代品。
您可以使用自动检测 url 的 UTTextView 或为 url 单独创建按钮。谢谢。