2015-10-12 174 views
0

我做了一個繼承自UIView的類。在那個課上,我想畫一個PNG圖像。但是,當我在viewcontroller中運行它時,它似乎沒有做任何事情。我讀過,我們必須使用setNeedsDisplay才能夠在viewcontroller中調用drawRect。它似乎沒有更新。從視圖控制器繪製類swift

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) 

    } 
} 
+0

瓷磚是平局或DrawTile? – Chiko

+0

你可以在啓動應用程序時看到圖像嗎? – Chiko

+0

我在啓動應用程序時看不到圖像。 – user187558

回答

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中(),一切都應該是好

+0

我試圖 設瓦片= DrawTile(幀:CGRectMake(0,0,50,50)) view.addSubview(瓦) ,它顯示該圖像。有沒有一種方法可以將框架初始化爲手機的整個尺寸,而不僅僅是0,0,50,50?然後我只想抓住尺寸並只打印png的一部分。 – user187558

+0

得到一個完整的屏幕使用:'let tile = DrawTile(frame:self.view.frame)'其中self.view是一個UIViewController的視圖。 – CarlHere