NSString draw(in: rect) 方法自己改变 rect

NSString draw(in: rect) method changes rect by itself

我正在尝试在 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) 中绘制它。所以它在运行时自己改变了矩形。

这是: 1)程序开始调用anotheR.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都不足以显示这么长的文字

SK_khan的解是正确的。如果你想让你的 anotherView 与控制器视图绑定相同,你可以选择在你的绘制方法中设置 CGRect 硬值,比如这个。

string.draw(in: CGRect(x: 100, y: 300, width: 50, height: 10), withAttributes:  [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24)])