【发布时间】:2018-04-04 18:02:27
【问题描述】:
我正在尝试在 UIView 中绘制一个字符串。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let anotheR: anotherView = anotherView(frame: view.bounds)
view.backgroundColor = UIColor.yellow
view.addSubview(anotheR)
anotheR.backgroundColor = UIColor.lightGray
anotheR.draw(CGRect(x: 100, y: 300, width: 50, height: 10))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class anotherView: UIView {
override func draw(_ rect: CGRect) {
let suprect = rect
var string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s." as NSString
string.draw(in: rect, withAttributes: [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFont(ofSize: 24)])
}
}
所以有一个视图,我覆盖了 UIViews 函数 draw(in:) 以在视图中写入一个字符串。所以它写了一个字符串,但没有指定矩形 (CGRect(x: 100, y: 300, width: 50, height: 10)) 。它只是在CGrect(x:0,y:0,width:frame.width,height:frame.height)中绘制它。所以它在运行时会自行改变 rect。
这里是: 1) 程序开始调用 anotherR.draw(CGRect(x: 100, y: 300, width: 50, height: 10)) 方法。
2) CGRect 以某种方式更改为 CGRect(x:0,y:0,width: frame.width, height: frame.height) 请也许有人知道发生了什么?它暴露了我写的所有代码。谢谢!
【问题讨论】:
-
请learn how drawing works (Paragraph The Drawing Cycle)。您不得自己致电
drawRect。当视图被标记为重绘时由框架调用。