Bobby Getka
Bobby Getka

Reputation: 83

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. The view does get updated, it just takes about 15 seconds. 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.

Upvotes: 3

Views: 12214

Answers (2)

Allan Weir
Allan Weir

Reputation: 628

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.

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.

Upvotes: 6

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

When you got data from server you can update UI into view with main queue as shown in below code:

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

}

Upvotes: 2

Related Questions