[iOS] 在循环中使用setNeedsDisplay来调用drawRect的方法

在iOS开发中,当视图内容改变需要重绘时,通常会调用setNeedsDisplay或setNeedsDisplayInRect方法。然而,这些方法并不会立即执行drawRect,而是在当前run loop结束后。为了实现动画效果,需确保视图属性的修改在run loop结束前完成,并在另一个run loop中进行重绘。本文探讨如何在循环中正确使用setNeedsDisplay以调用drawRect,确保视图更新的异步处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


今天想做一个根据进度变化的动画,因此写了一个循环做实验。大致的结构就是在一个循环内不断更新一个变量并且更新动画。

但是发现每次都是循环结束的时候动画才执行,即只执行了最后一次。

然后去google,发现了这样一段话。


When a content of the view is changed and needs to be redrawn you can invalidate the view by calling setNeedsDisplay: or setNeedsDisplayInRect: methods. When one of these method is called, it says the system to redraw the view. Before drawing the requested view the system will wait for the current run loop to finish. This delay help us to do further changes to the view's properties or you can even add or remove views from the hierarchy and finally all the changes will get effect at the end of the current run loop.


上面标红的地方是重点,就是只有当前runloop结束的时候才会重新绘制动画。而且drawRect方法不能直接调用。


每一个线程都有一个runloop,只要让程序在一个runloop中循环,在另一个runloop中重绘就好了。

所以方法如下:

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        float progress = 0.0f;
        while (progress < 1.0f) {
            //更新变量
            dispatch_async(dispatch_get_main_queue(), ^{
                //更新动画
            });
    <span style="white-space:pre">		</span>//这里可以等待一下,防止太快
        }
    });



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值