OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UIAlertController 消息上显示 HTML [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:43
标题: ios - 在 UIAlertController 消息上显示 HTML

我想知道是否有办法在 UIAlertController 的消息中显示 HTML。

Android 有办法做到这一点,但我找不到在 iOS 上做同样事情的方法。我现在正在使用 Swift 3。



Best Answer-推荐答案


我不想在我的项目中添加更多的类,所以我一直在寻找一种更直接的方法来做到这一点。我找到了this link很有帮助。

我的最终代码如下所示:

-(void)viewDidAppearBOOL) animated {
    NSString *htmlString = @"<html><body><h1>HTML, baby!</h1><p>Try it.<p>You'll totally<br />love it.<br /><b>Sample Bold text</b></body></html>";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle"Welcome"
                                                                     message:htmlString
                                                              preferredStyle:UIAlertControllerStyleAlert];
    NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
               options{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
    documentAttributes:nil error:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        // OK button tappped.
        [self dismissViewControllerAnimated:YES completion:^{ }];
    }];
    [alert setValue:attributedStr forKey: @"attributedMessage"];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:true completion:nil];
}

我包含了 viewDidAppear 声明,因为我在很长一段时间内都有一个错字,导致 UIAlertController 无法出现,因为整个函数从未被调用。

关于ios - 在 UIAlertController 消息上显示 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858762/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4