Ios NSString draw(in:rect)方法会自行更改rect
我正试图在视图中画一条线Ios NSString draw(in:rect)方法会自行更改rect,ios,swift,nsstring,Ios,Swift,Nsstring,我正试图在视图中画一条线 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)
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) 程序开始调用另一个.draw(CGRect(x:100,y:300,width:50,height:10))方法。
2) CGRect以某种方式更改为CGRect(x:0,y:0,width:frame.width,height:frame.height)
拜托也许有人知道发生了什么?它公开了我写的所有代码。谢谢大家! 实际上drawRect捕获视图的框架并根据其尺寸进行绘制,您不应该显式地调用它,您只需要指定这一行
let anotheR: anotherView = anotherView(frame: view.bounds)
或者改成
let anotheR: anotherView = anotherView(frame:CGRect(x: 100, y: 300, width: 50, height: 10))
另外,给它一个合适的宽度和高度,分别为50和10不足以显示如此长的文本来自Sku khan的解决方案是正确的。如果希望将另一个视图的绑定与控制器视图的绑定保持一致,则可以选择在绘制方法中设置CGRect硬值,如下所示
string.draw(in: CGRect(x: 100, y: 300, width: 50, height: 10), withAttributes: [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24)])
请您不能自己调用drawRect
。当视图被标记为重绘时,框架将调用它。