【问题标题】:NSString draw(in: rect) method changes rect by itselfNSString draw(in: rect) 方法自己改变 rect
【发布时间】: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) 请也许有人知道发生了什么?它暴露了我写的所有代码。谢谢!

【问题讨论】:

标签: ios swift nsstring


【解决方案1】:

SK_khan 的解决方案是正确的。如果您想保持 anotherView 绑定与控制器视图绑定相同,您可以选择像这样在 draw 方法中设置 CGRect 硬值。

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

【讨论】:

    【解决方案2】:

    其实drawRect是捕获view的frame并根据它的尺寸进行绘制,你不应该显式调用它,你只需要指定这一行

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

    或者改成

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多