简体   繁体   English

从viewcontroller类绘图

[英]drawing from viewcontroller class swift

I made a class that inherits from UIView. 我做了一个继承自UIView的类。 In that class I want to draw a png image. 在该课程中,我想绘制一个png图像。 However, when I run it in my viewcontroller, it doesn't seem to do anything. 但是,当我在viewcontroller中运行它时,它似乎没有任何作用。 I read that we had to use setNeedsDisplay to be able to get the drawRect to be called in the viewcontroller. 我读到我们必须使用setNeedsDisplay才能在视图控制器中调用drawRect。 It doesn't seem to update. 它似乎没有更新。

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)

    }
}

Are you initializing your view somewhere? 您要在某处初始化视图吗? drawRect() will only get called when you initialize your custom view and add it to your ViewController view. 只有在初始化自定义视图并将其添加到ViewController视图时,才会调用drawRect()。 So it should look something like this: 所以它应该看起来像这样:

    func createCustomView(){

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

    self.view.addSubview(customView)

}

do it in viewDidLoad() and everything should be ok 在viewDidLoad()中做到这一点,一切都应该没问题

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

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