如何在swift中更改子视图的背景颜色?
问题描述:
我创建了一个新的子视图类来绘图 我已经覆盖函数drawRect(),但我不能改变 子视图的背景颜色我用背景方法,但它没有工作!如何在swift中更改子视图的背景颜色?
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()
}
}
答
您需要在drawRect之前设置背景颜色。在你调用drawRect的时候,背景已经被绘制出来了。如果您需要能够在drawRect中设置背景颜色,就可以自己绘制背景颜色,就像绘制蓝色矩形轮廓的方式一样。
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()
}
}
答
我创建了一个“准备”功能,我称之为视图时创建的:
class myView: UIView {
func prepare() {
backgroundColor = UIColor.blueColor()
}
override func drawRect(rect: CGRect) {
// custom stuff
}
}
用法(此函数返回在的tableview头以使用新的视图):
let myView = myView()
myView.prepare()
return myView
我确定有一个更简洁的方法来做到这一点,但我不想混淆初始值设定项,创建扩展项或者使用图层。这很简单,很有效。就我所能看到的唯一缺点是,你不能动态地确定drawrect:time的颜色。但如果你知道初始化过程中的颜色,这应该可以工作。
享受。
答
沿着加里麦金的想法,这为我工作。我有GameBoardView
类别的gameBoard
,它是UIView
的子类别。
当我做了这样它不会覆盖我的故事板设置颜色:
class GameBoardView: UIView {
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.greenColor()
}
}
但是当我把该行的ViewController
的viewWillAppear()
方法,它的工作原理:
class ViewController: UIViewController {
// some code
override func viewWillAppear(animated: Bool) {
// more code
gameBoard.backgroundColor = UIColor.greenColor()
// some other code
}
// still more code
}
希望它有帮助
答
您不必在创建此视图时设置背景颜色。
创建视图之后的任何时间,只需调用视图这行代码,它的背景颜色将变为
view.backgroundColor = UIColor.blackColor()
我试过,但没有奏效 – abedAssa