我什么时候需要在 iOS 中调用 setNeedsDisplay? [英] When do I need to call setNeedsDisplay in iOS?

查看:24
本文介绍了我什么时候需要在 iOS 中调用 setNeedsDisplay?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建 iOS 应用程序时,我对何时需要调用 setNeedsDisplay 感到困惑?我知道它与更新/重绘用户界面有关;但是,每次我改变我的观点时都需要调用它吗?

When creating an iOS app, I'm confused as to when exactly I need to call setNeedsDisplay? I know that it has something to do with updating/redrawing the UI; however, do I need to call this every time I change any of my views?

比如我是否需要调用它:

For example, do I need to call it:

  • 以编程方式更改文本字段中的文本后
  • 何时更改视图的背景?
  • 当我在 viewDidLoad 中进行更改时?
  • viewDidAppear 怎么样?

有人能给我一些关于何时使用这种方法的一般指南吗?

Could someone give me some general guidelines regarding when to use this method?

推荐答案

如果您在 UIView 的子类中覆盖 drawRect,您应该只调用 setNeedsDisplay,UIView 基本上是在屏幕上绘制某些内容的自定义视图,例如线条、图像或形状像一个矩形.

You should only be calling setNeedsDisplay if you override drawRect in a subclass of UIView which is basically a custom view drawing something on the screen, like lines, images, or shapes like a rectangle.

因此,当您更改此绘图所依赖的几个变量时,您应该调用 setNeedsDisplay,并且为了表示该更改的视图,您需要调用此方法,该方法将在内部调用 drawRect 并重绘组件.

So you should call setNeedsDisplay when you make changes to few variables on which this drawing depends and for view to represent that change , you need to call this method which internally will give a call to drawRect and redraw the components.

当你添加一个 imageView 或一个 UIButton 作为子视图或对任何子视图进行更改时,你不需要调用这个方法.

When you add an imageView or a UIButton as a subview or make changes to any subview, you need not call this method.

示例:

您有一个显示移动圆圈的视图,您可以触摸并移动它,也可以是基于计时器的动画.现在为此,您将需要一个自定义视图,该视图在给定的中心和给定的半径处绘制一个圆.这些被保留为实例变量,它们被修改为通过改变圆心来移动圆或通过增加半径来使其变大.

You have a view that shows a moving circle, either you touch and move it, or may be timer based animation. Now for this, you will need a custom view that draws a circle at given center and with given radius. These are kept as instance variables which are modified to move the circle by changing its center or make it bigger by increasing radius of it.

现在在这种情况下,您可以在循环和计时器中修改这些变量(中心或半径),或者可以通过您的手指在 touchesEnded 和 touchesMoved 方法中进行修改.要反映此属性的更改,您需要重绘此视图,您将为其调用 setNeedsDisplay.

Now in this case either you will modify these variables(centre or radius) in a loop and timer Or may be by your fingers in touchesEnded and touchesMoved methods. To reflect the change in this property you need to redraw this view for which you will call setNeedsDisplay.

这篇关于我什么时候需要在 iOS 中调用 setNeedsDisplay?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆