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()
    }
}

Tags:

Ios

Iphone

Swift