How to Reload a UI View's Content Swift

How to reload a UiView in iOS?

It depends. Typical "complex" views that might display large amounts of data (like UITableView or UIPickerView) use a data source protocol that allows them to fetch data on demand. In this case, you need to inform the view that new / modified data is available, hence call reloadData. Then, the view will ask the data source for the data to be displayed.

Primitive views (like UILabel) just provide a property (like text) which you need to set / update, and the view will then redisplay the data.

How to refresh a View in Swift 3

Write all the code in viewWillappear() . This will solve your issue.

swift reload views when value changed

The best way to approach this problem is by solving UI updates in the

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

// Add you code here
}

Of your MainViewController.

Reloading a ViewController

You really don't need to do:

[self.view setNeedsDisplay];

Honestly, I think it's "let's hope for the best" type of solution, in this case. There are several approaches to update your UIViews:

  1. KVO
  2. Notifications
  3. Delegation

Each one has is pros and cons. Depending of what you are updating and what kind of "connection" you have between your business layer (the server connectivity) and the UIViewController, I can recommend one that would suit your needs.

Reload/Update View In Swift

if you want to trigger layouting or just drawing there is setNeedsLayout and setNeedsDisplay

There is no built-in method to reload custom data (on iOS)


so do a reload and inside a reload -- call setNeedsDisplay

import UIKit

protocol MyViewDelegate {
func viewString() -> String;
}

class MyView : UIView {
var myViewDelegate : MyViewDelegate?
private var str : String?

func reloadData() {
if myViewDelegate != nil {
str = myViewDelegate!.viewString()
}
self.setNeedsDisplay()
}

override func drawRect(rect: CGRect) {
UIColor.whiteColor().setFill()
UIRectFill(self.bounds)
if str != nil {
let ns = str! as NSString
ns.drawInRect(self.bounds, withAttributes: [NSForegroundColorAttributeName: UIColor.blueColor(), NSFontAttributeName: UIFont.systemFontOfSize(10)])
}
}
}


class ViewController: UIViewController, MyViewDelegate {
func viewString() -> String {
return "blabla"
}

var v : MyView!

override func viewDidLoad() {
super.viewDidLoad()

v = MyView(frame: self.view.bounds)
self.view.addSubview(v)

v.myViewDelegate = self;
}

override func viewWillAppear(animated: Bool) {
v.reloadData()
}
}


Related Topics



Leave a reply



Submit