简体   繁体   English

我真的需要自定义UIView中的drawRect()吗?

[英]Do I really need drawRect() in custom UIView?

I am new to iOS and trying to understand the use for drawRect() in custom UIViews, so I have simple custom view which I initialize from code.I want to update its colors for instance and I see two approaches as shown below. 我是iOS新手并试图理解自定义UIViews中drawRect()的用法,所以我有一个简单的自定义视图,我从代码初始化。我想更新它的颜色,我看到两种方法,如下所示。 Which one should I use and why? 我应该使用哪一个?为什么?

//VController
CustomView *cv = [[CustomView alloc] initWithFrame:...]
...
[cv updateColors];

//CustomView
-(id) initWithFrame {}
-(id) initWithCoder  {}
-(void) updateColors(UIColor *color){  ----(1)
  ...Draw here with new color ...
   view1.backgroundColor = color;
   view2.backgroundColor = color;

 }
- (void) drawRect{
 ... draw here with new color ... ---------(2)
   view1.backgroundColor = color;
   view2.backgroundColor = color;
 }

If all you want to do is change the background color of this view or some of its subviews, you absolutely should not misuse drawRect: for this. 如果想要做的是改变这种看法或一些子视图的背景颜色,你绝对应该滥用drawRect:此。 drawRect: is for when you want to draw the view (ie its content) when the system believes its needs refreshing; drawRect:用于当系统认为需要刷新时想要绘制视图(即其内容); it is called at many and unpredictable times, and you don't need that - you just need to change the background color, a feature of the view, on demand. 它在许多不可预测的时间被调用,你不需要它 - 你只需要根据需要改变背景颜色,即视图的一个特征 Similarly drawRect: is not the place to perform management of subviews. 类似地, drawRect: 不是执行子视图管理的地方。

But if you are going to draw the view's content (eg the view displays a circle and you need to draw that circle to portray the view) then you must use drawRect: for that; 但是,如果你绘制视图的内容(例如视图中显示一个圆圈,你需要绘制圆圈描绘的观点),那么你必须使用drawRect:是什么; it is the only place where the view gets a chance to draw itself. 它是视图有机会吸引自己的唯一场所。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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