如果初始帧是CGRectZero,则自定义UIView的drawRect从不调用
我有一个非常简单的UIView自定义子类:
#import "BarView.h" #import @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
如果我在这个类上使用一些非零的rect调用initWithFrame:rect,它可以正常工作; 但是当我调用initWithFrame:CGRectZero时,即使在我将视图的帧修改为非零rect之后,也会调用drawRect。
我当然理解为什么一个零帧的视图永远不会有它的drawRect:被调用,但为什么它甚至在帧被改变之后才被调用?
快速浏览Apple文档即可
更改框架矩形会自动重新显示视图而不调用其drawRect:方法。 如果希望UIKit在框架矩形更改时调用drawRect:方法,请将contentMode属性设置为UIViewContentModeRedraw。
这是在frame属性的文档中:
https://developer.apple.com/documentation/uikit/uiview/1622621-frame?language=objc
如果你想让视图重绘,只需在它上面调用setNeedsDisplay你应该没问题(或者,正如文档所说,你可以将它设置为UIViewContentModeRedraw,但这取决于你)
- 在Swift中从相机裁剪图像,而不移动到另一个ViewController
- iOS查询通过相册MPMediaEntityPersistentID有时会带回没有歌曲
- 根据对应于特定属性的另一个数组中的值对对象数组sorting
- 如何将UITableViewCell与UITableView的底部alignment?
- IOS / Xcode / Coredata:当模态控制器被解雇时,如何强制从NSFetchedResults控制器重新加载
- 在iOS中创build随机的128位AESencryption密钥
- 如何在Interface Builder中使用自动布局创build键盘附件视图?
- 重新创建Siri Button Glow动画
- 如何在uiwebview中调用https url?