Reputation: 100
I created a new subview class to make drawing I have override the function drawRect() but i can't change the background color of the subview i used background method but it did'n work !
import UIKit
class AbedView:UIView {
override func drawRect(rect: CGRect) {
let color = UIColor.blueColor()
// Do any additional setup after loading the view, typically from a nib.
let cgrRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let newView = UIBezierPath(rect: cgrRect)
print(newView.bounds)
color.set()
newView.lineWidth = 5
newView.stroke()
self.backgroundColor = UIColor.blackColor()
}
}
Upvotes: 1
Views: 5145
Reputation:
You don't have to set the background color when you create this view.
Anytime after the view is created, simply call this line of code on the view and it's background color will be changed
view.backgroundColor = UIColor.blackColor()
Upvotes: 2
Reputation: 967
Following along Gary Makin's idea, this worked for me. I have a view gameBoard
of class GameBoardView
which is a subclass of UIView
.
When I did it this way it does not override the colour I set in the storyboard:
class GameBoardView: UIView {
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.greenColor()
}
}
But when I put that line in the ViewController
's viewWillAppear()
method it works:
class ViewController: UIViewController {
// some code
override func viewWillAppear(animated: Bool) {
// more code
gameBoard.backgroundColor = UIColor.greenColor()
// some other code
}
// still more code
}
Hope it helps
Upvotes: 1
Reputation: 3169
You need to set the background color before drawRect. By the time your drawRect is called, the background has already been drawn. If you need to be able to set the background color in the drawRect, just draw it yourself, just like the way you are drawing the blue rectangle outline.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.blackColor()
}
class AbedView:UIView {
override func drawRect(rect: CGRect) {
let color = UIColor.blueColor()
let cgrRect = CGRect(x: 0, y: 0, width: 100, height: 100)
let newView = UIBezierPath(rect: cgrRect)
print(newView.bounds)
color.set()
newView.lineWidth = 5
newView.stroke()
}
}
Upvotes: 4
Reputation: 1048
I created a "prepare" function, which I call when the view is created:
class myView: UIView {
func prepare() {
backgroundColor = UIColor.blueColor()
}
override func drawRect(rect: CGRect) {
// custom stuff
}
}
Usage (this is returning the new view to use in a tableview header):
let myView = myView()
myView.prepare()
return myView
I'm sure there's a more concise way to do this, but I didn't want to mess with the initializers, create an extension, or muck around with layers. This is simple and works. The only downside as far as I can see is that you can't dynamically determine the color at drawrect: time. But if you know the color during initialization this should work.
Enjoy.
Upvotes: 0