Swift-一种强制重绘UIScrollView的方法

时间:2018-07-25 09:34:05

标签: ios swift uiview

我有一个UIViewController,其中有一个UIScrollView,还有一个函数(build())在UIView中绘制了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

谢谢!

1 个答案:

答案 0 :(得分:0)

没有重绘UIScrollView的方法,那么您唯一需要做的就是:

  1. 将视图添加到UIScrollView
  2. 设置contentSize中的UIScrollView,以便允许用户平移并查看UIScrollView的所有内容

您在代码中所做的事情似乎还可以,因为您同时在做上面列出的两件事。

问题是您的t是否被隐藏:

if t.isHidden == true {
    continue
}

或者您正在后台线程的其他地方调用build()方法

为确保您没有这样做,您可以将assert(Thread.isMainThread, "Never call me on background thread")添加为build()方法的第一行