简体   繁体   中英

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

I am trying to draw a string in a 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)])

}
}

So there is a view and I overrode UIViews function draw(in:) to write a string in a view. So it writes a string but not it specified rectangle (CGRect(x: 100, y: 300, width: 50, height: 10)) . It just draw it in CGrect(x:0,y:0,width: frame.width, height: frame.height). So it changes rect by itself during runtime.

Here it is: 1) programm begins to call anotheR.draw(CGRect(x: 100, y: 300, width: 50, height: 10)) method. 在此处输入图片说明

2) CGRect somehow changes to CGRect(x:0,y:0,width: frame.width, height: frame.height) 在此处输入图片说明 Please maybe someone knows whats happen? It exposed all code I had wrote. Thank you!

The solution from SK_khan is correct. In case if you like to keep your anotherView bound same with controller view bound, you can choose to set the CGRect hard value inside your draw method like this.

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

Actually drawRect captures the frame of the view and draws according to it's dimensions , you should not call it explicitly , You only need to specify this line

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

Or change it to

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

Also give it a suitable width and height 50 , 10 respectively are not sufficient to display such long text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM