如果初始帧是CGRectZero,则自定义UIView的drawRect从不调用 [英] Custom UIView's drawRect never called if initial frame is CGRectZero

查看:101
本文介绍了如果初始帧是CGRectZero,则自定义UIView的drawRect从不调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的UIView自定义子类:

I've got a pretty simple custom subclass of UIView:

#import "BarView.h"
#import <QuartzCore/QuartzCore.h>

@implementation BarView

@synthesize barColor;

- (void)drawRect:(CGRect)rect
{
    NSLog(@"drawRect");
    // Draw a rectangle.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, self.barColor.CGColor);
    CGContextBeginPath(context);
    CGContextAddRect(context, self.bounds);
    CGContextFillPath(context);
}

- (void)dealloc
{
    self.barColor = nil;

    [super dealloc];
}

@end

如果我调用initWithFrame:rect在这个有一些非零rect的类上,它工作正常;但是当我调用initWithFrame:CGRectZero时,即使我将视图的框架修改为非零的矩形,也会调用drawRect。

If I call initWithFrame:rect on this class with some non-zero rect, it works fine; but when I call initWithFrame:CGRectZero, drawRect is -never- called, even after I modify the view's frame to a non-zero rect.

我当然理解为什么一个视图使用零帧永远不会有它的drawRect:调用,但为什么它甚至在帧被更改之后才被调用?

I certainly understand why a view with a zero frame would never have its drawRect: called, but why is it never called even after the frame is changed?

推荐答案

快速浏览一下Apple文档说这个

A quick look at the Apple docs says this


更改框架矩形会自动重新显示视图而不调用其drawRect:方法。如果你希望UIKit在框架矩形更改时调用drawRect:方法,请将contentMode属性设置为UIViewContentModeRedraw。

Changing the frame rectangle automatically redisplays the view without calling its drawRect: method. If you want UIKit to call the drawRect: method when the frame rectangle changes, set the contentMode property to UIViewContentModeRedraw.

这是在框架属性的文档:

https ://developer.apple.com/documentation/uikit/uiview/1622621-frame?language = objc

This is in the documentation for the frame property:
https://developer.apple.com/documentation/uikit/uiview/1622621-frame?language=objc

如果您想要重绘视图,只需调用setNeedsDisplay并且你应该没问题(或者,正如文档所说,你可以将它设置为UIViewContentModeRedraw,但这取决于你)

If you want the view to redraw, just call setNeedsDisplay on it and you should be fine (or, as the docs say, you can set it to UIViewContentModeRedraw, but it is up to you)

这篇关于如果初始帧是CGRectZero,则自定义UIView的drawRect从不调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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