[英]Show hyperlink in message in UIAlerController in Objective-c
我想在 Objective-c 的 UIAlertController 中顯示一些帶有超鏈接的文本作為消息。 如果我單擊該超鏈接,它應該重定向我以在 Safari 中打開該鏈接。
我不想在第三方庫中使用。
任何想法我怎么能做到這一點?
沒有直接的方法將其顯示為超鏈接。 您可以添加自己的消息對話框,也可以在 UIAlertController 中添加一個按鈕來打開超鏈接。
步驟 1. 從您的消息字符串中獲取 URL
NSURL *url;
NSString *string = @"This is a sample of a http://example.com/index.html sentence with a URL within it.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
url = [match URL];
NSLog(@"found URL: %@", url);
}
}
步驟 2. 顯示您的警報消息
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@“Message”
message:@"Would you like to open link?”
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:@“Open using Safari” Link
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
UIApplication *app = [UIApplication sharedApplication];
if ([app canOpenURL:url])
{
[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:^(BOOL success) {
//completion codes here
}];
}
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:@"No"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:yesButton];
[alert addAction:noButton];
[self presentViewController:alert animated:YES completion:nil];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.