我有一个 UIViewController
,其中有一个 UIScrollView
,还有一个用于绘制 UIView 的函数 (
位于 build()
) UIScrollView
中。
问题: UIViewController
中什么也没有出现,但是当我滚动时(即当我更新 UIScrollView
时),UIView
,我想要的,出现。
我尝试了 setNeedsDisplay()
来强制重绘,但它不起作用...
帮助您理解问题的视频: https://vimeo.com/user87689481/review/281597574/3cccb78dc1
这是UIViewController
的代码:
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var body: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationController?.navigationBar.prefersLargeTitles = true
navigationController?.navigationItem.largeTitleDisplayMode = .always
DispatchQueue.global(qos: .background).async {
while !Home.accessories.isInitialized {}
DispatchQueue.main.async {
self.build(Home.accessories.toUIView())
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func build(_ s: [UISectionView]) {
let topMargin = 10
let rightMargin = 10
let leftMargin = 10
let space = 5
let heightItem = 60
var b = topMargin
for t in s {
if t.isHidden == true {
continue
}
if t.title != nil {
let f = UIFont(name: "Helvetica", size: 20)
let l = UILabel(frame: CGRect(x: rightMargin, y : b, width: Int(UIScreen.main.bounds.width) - (rightMargin + leftMargin), height: Int(f!.lineHeight)))
l.font = f
l.text = t.title
body.addSubview(l)
b = b + Int(f!.lineHeight) + space
}
for i in t.items {
body.addSubview(i.getView(frame: CGRect(x: rightMargin, y: b, width: Int(UIScreen.main.bounds.width) - (rightMargin + leftMargin), height: heightItem), view: self))
b = b + heightItem + space
}
}
body.contentSize = CGSize(width: UIScreen.main.bounds.width, height: CGFloat(b))
//a code to force body (UIScrollView) to refresh/relaod/redraw/update/...
}
}
希望我们能帮助我=D
提前致谢!
最佳答案
没有方法可以重绘 UIScrollView
,那么您只需要做的就是:
- 将 View 添加到
UIScrollView
- 设置
contentSize
UIScrollView
的这样用户就可以平移并查看UIScrollView
的所有内容
您在代码中所做的事情似乎没问题,因为您正在做上面列出的两件事。
问题是如果你的 t
s 被隐藏:
if t.isHidden == true {
continue
}
或者您正在调用build()
后台线程上其他地方的方法
为了确保您没有这样做,您可以添加 assert(Thread.isMainThread, "Never call me on background thread")
作为 build()
中的第一行方法
关于ios - Swift - 强制重绘 UIScrollView 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51515561/