简体   繁体   English

如何强制UIView更新

[英]How to force a UIView to update

I am working on an application that is downloading JSON data from a server, and then displays it on a UIView. 我正在一个正在从服务器下载JSON数据,然后将其显示在UIView上的应用程序上。 The view does get updated, it just takes about 15 seconds. 该视图确实得到更新,只需要15秒钟。 I have tested to make sure it is not the download that is delaying the update, and if I change the view's background color as I am adding data it also waits to update. 我已经进行测试,以确保不是下载延迟了更新,并且如果在添加数据时更改视图的背景色,它也会等待更新。 Am I correct in thinking that it is the view not updating, or is it something else? 我是否认为视图未更新是正确的,还是其他? How do I force the view to update? 如何强制更新视图? Thanks. 谢谢。

var newView = CustomView(product: products[0],descriptive: false)
        contentView.addSubview(newView)

        let backHeight = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Height, multiplier: 0.2, constant: 0)
        let backWidth = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)

        let backXPosition = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant:0 )
        let backYPosition = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: colorLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)
        view.addConstraints([backHeight,backWidth,backXPosition,backYPosition])

This is how I am adding the items to the view. 这就是我将项目添加到视图的方式。

Do you have a sample of the code where you're displaying the data in the view? 您是否具有在视图中显示数据的代码示例?

You can trigger a view to update by calling 您可以通过调用触发视图更新

view.setNeedsDisplay() //Updates any drawing, including that in drawRect()

and

view.setNeedsLayout() //Triggers layoutSubviews()

But I don't think either of those will help as if you're adding new views they should show up without calling those. 但是我认为这两种方法都不会有帮助,好像您要添加新视图而无需调用这些视图那样。 Unless you're on a different thread like Dharmesh suggested. 除非您使用Dharmesh建议的其他线程。

Make sure you're adding the views to the parent, and make sure you're setting a frame on them too as if they're labels they might not appear without a frame being set. 确保将视图添加到父视图,并确保也在其上设置框架,就好像它们是标签一样,如果未设置框架,它们可能不会出现。

When you got data from server you can update UI into view with main queue as shown in below code: 从服务器获取数据后,可以使用主队列将UI更新到视图中,如以下代码所示:

dispatch_async(dispatch_get_main_queue()) {
    //Update your UI here

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM