NSString draw(in:rect)方法自行更改rect

时间:2018-04-04 18:02:28

标签: ios swift nsstring

我正在尝试在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(在:)中在视图中写一个字符串。所以它写了一个字符串,但没有指定矩形(CGRect(x:100,y:300,width:50,height:10))。它只是在CGrect(x:0,y:0,width:frame.width,height:frame.height)中绘制它。因此它在运行时自行更改rect。

这是: 1)程序开始调用 anotheR.draw(CGRect(x:100,y:300,width:50,height:10))方法。  enter image description here

2)CGRect以某种方式更改为CGRect(x:0,y:0,width:frame.width,height:frame.height)enter image description here 也许有人知道什么事发生?它暴露了我写的所有代码。谢谢!

2 个答案:

答案 0 :(得分:1)

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)])

答案 1 :(得分:0)

实际上drawRect捕获视图的框架并根据它的尺寸绘制,你不应该明确地调用它,你只需要指定这一行

 let anotheR: anotherView = anotherView(frame: view.bounds)

或将其更改为

 let anotheR: anotherView = anotherView(frame:CGRect(x: 100, y: 300, width: 50, height: 10))

同时给它一个合适的宽度和高度50,10分别不足以显示这么长的文字