使用OC语言开发一个UIAlertController弹窗,要求内容包含超链接,可点击跳转Web页面
时间: 2024-05-12 13:21:14 浏览: 9
UIAlertController弹窗一般用于提示用户某些信息或进行一些简单的操作。但是,它并不支持在内容中包含超链接。因此,我们需要自定义UIAlertController弹窗,并在其中添加一个可点击的UILabel来实现超链接跳转。
以下是示例代码:
```
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题"
message:@"这是一个带超链接的提示框"
preferredStyle:UIAlertControllerStyleAlert];
// 创建富文本字符串,并添加超链接
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@"点击这里跳转到百度"];
[attributedStr addAttribute:NSLinkAttributeName value:@"http://www.baidu.com" range:NSMakeRange(0, attributedStr.length)];
// 创建一个可点击的UILabel
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
label.attributedText = attributedStr;
label.textAlignment = NSTextAlignmentCenter;
label.userInteractionEnabled = YES;
[label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabel:)]];
// 将UILabel添加到UIAlertController的view中
[alertController.view addSubview:label];
// 创建并添加UIAlertAction
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了确定按钮");
}];
[alertController addAction:okAction];
// 显示UIAlertController
[self presentViewController:alertController animated:YES completion:nil];
```
在以上代码中,我们创建了一个UIAlertController,并在其中添加了一个UILabel,将UILabel的attributedText设置为带有超链接的富文本字符串,然后添加了一个手势识别器,当用户点击UILabel时,会调用tapLabel方法,在该方法中使用UIApplication打开URL来跳转到指定的网页。最后,我们添加了一个UIAlertAction,将UIAlertController显示出来。
以下是tapLabel方法的示例实现:
```
- (void)tapLabel:(UITapGestureRecognizer *)gestureRecognizer {
UILabel *label = (UILabel *)gestureRecognizer.view;
NSRange range = [label.attributedText.string rangeOfString:@"点击这里跳转到百度"];
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
if (range.location != NSNotFound) {
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}
}
}
```
在tapLabel方法中,我们首先获取被点击的UILabel,然后查找UILabel的attributedText中是否包含指定的文本,如果包含,则使用UIApplication打开URL来跳转到指定的网页。