从viewcontroller类swift绘制

时间:2015-10-12 11:30:35

标签: ios swift drawrect setneedsdisplay

我创建了一个继承自UIView的类。在那堂课中,我想绘制一个png图像。但是,当我在我的viewcontroller中运行它时,它似乎没有做任何事情。我读到我们必须使用setNeedsDisplay才能在viewcontroller中调用drawRect。它似乎没有更新。

class MyView: UIViewController{
    let tile = DrawTile()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func Pressed(sender: AnyObject) {
         tile.setNeedsDisplay()

    }
}

class Draw: UIView {

    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        let image = UIImage(named: "test.png")
        let location = CGPointMake(0, 0)
        image?.drawAtPoint(location)

    }
}

1 个答案:

答案 0 :(得分:0)

您是否在某处初始化视图?只有在初始化自定义视图并将其添加到ViewController视图时才会调用drawRect()。所以看起来应该是这样的:

    func createCustomView(){

    customView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    customView.something = something

    self.view.addSubview(customView)

}

在viewDidLoad()中执行,一切都应该没问题