html - 无法通过 NSAttributedString 使 <img> 适合 UITextView/HTML 中的屏幕宽度

标签 html ios css swift uitextview

我尝试将带有图像的 HTML 加载到 UITextView,但图像不适合屏幕宽度,它们太大了。 IMG 标签和 CSS 的属性宽度没有帮助:(

代码如下:

            var content = "<html><head><meta charset='utf-8'><title>«Первый поворот налево или направо?» Секреты успеха Льюиса Хэмилтона</title><style>img {max-width: '100%'; width: '100%'; height: auto;}body{ color:red }</style></head><body><p>Иногда его превосходство заметно сразу – как в случае с потрясающей скоростью вхождения в первый поворот на Гран При Австралии нынешнего года, а иногда не столь очевидно.</p><p><img src='http://autosport.com.ru/files/feature/2018/06/29/ba7222d642a69863db32ec8e5d2e8b8f.jpg' alt='Льюис Хэмилтон © autosport.com'/>Льюис Хэмилтон</p>"
        let htmlData = NSString(string: content).data(using: String.Encoding.unicode.rawValue)
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
        let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)
        txtView.attributedText = attributedString

最佳答案

设置 CSS imgmax-width, max-height, width, height 到 100% 对我有用。

let content: String = "<!DOCTYPE html><html>" +
    "<head>" +
    "<meta charset='UTF-8'>" +
    "<style type='text/css'>" +
    "body {" +
    "margin: 0;" +
    "padding: 0;" +
    "}" +
    "img{" +
        "max-width: 100%;" +
        "max-height: 100%;" +
        "width: 100%;" +
        "height: 100%;" +
    "}" +
    "</style>" +
    "</head>" +
    "<body></body></html>"

关于html - 无法通过 NSAttributedString 使 <img> 适合 UITextView/HTML 中的屏幕宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663862/

相关文章:

html - 覆盖字体和大小

javascript - 未捕获的类型错误 : Cannot read property 'root' of undefined

html - 如何避免浏览器在我的注册表中预填充字段?

ios - `UIImage` 类的指定初始化程序是什么?

css - 两次导入相同的 less 文件时出现 Dotless MVC 捆绑问题

java - 菜单项重复

iphone - 添加 NSArrays 到 NSDictionary

ios - 从另一个 ViewController 访问数组并对其进行排序

html - <窗体>是否中断高度 :100%?

html - 将 HTML 按钮转换为链接的最佳方式