【发布时间】:2018-01-29 06:19:29
【问题描述】:
我是 Swift 新手(使用 4 个版本)。 我有 HTML 文本,里面可以包含图片链接。
some text
<img src=""/>
some text
我想让内容可滚动,所以我将容器(简单的 UIView)包装到 UIScrollview。
然后我将 HTML 文本解析为多个部分:“文本”和“图像链接”到一个数组(数据和类型)中。 然后遍历我观察的那个数组,如果类型是文本 - 我输入带有约束的标签:
如果它是容器的第一个元素,那么左、上、右、下是匹配的。 如果不是,则 top 匹配容器中前一个视图的底部(如链)。
但由于某种原因,它不起作用。 我究竟做错了什么? 我把我的代码:
var lastView = containerView!
var label : UILabel
var imageView : UIImageView
for item in articleContent {
if (item.type == RenderDetailBlogObject.TYPE_TEXT) {
label = UILabel()
label.numberOfLines = 0
label.attributedText = item.data.html2AttributedString
containerView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leftAnchor.constraint(equalTo: containerView.leftAnchor),
label.rightAnchor.constraint(equalTo: containerView.rightAnchor),
])
if (lastView == containerView) {
print("ADDING LABEL lastView == containerView")
label.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0).isActive = true
} else {
print("ADDING LABEL lastView != containerView")
label.topAnchor.constraint(equalTo: lastView.bottomAnchor, constant: 0.0).isActive = true
}
lastView = label
} else {
imageView = UIImageView()
imageView.sd_setImage(with: URL(string: item.data))
containerView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.leftAnchor.constraint(equalTo: containerView.leftAnchor),
imageView.rightAnchor.constraint(equalTo: containerView.rightAnchor),
])
if (lastView == containerView) {
print("ADDING AN IMAGE lastView == containerView")
imageView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0).isActive = true
} else {
print("ADDING AN IMAGE lastView != containerView")
imageView.topAnchor.constraint(equalTo: lastView.bottomAnchor, constant: 0.0).isActive = true
}
lastView = imageView
}
lastView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0)
}
编辑: 代码似乎是正确的,并且视图添加正确,但约束不允许滚动视图。
我测试了约束(中心 Y - 向它添加了 200 多个范围并开始滚动,但它是硬编码值,所以它可能有更合法的解决方案吗?) 没有这个约束,它就会出错并且根本不起作用。
【问题讨论】:
-
使用
UIWebview或WKWebView显示html -
它没有提供任何定制的可能性
标签: ios swift uiscrollview autolayout