UIToolbar 类别drawRect:不起作用

发布于 2024-09-29 20:58:54 字数 362 浏览 7 评论 0原文

我尝试了以下操作:

@implementation UIToolbar (Image)

-(void)drawRect:(CGRect)rect {
    UIImage *img  = [UIImage imageNamed: @"navigationBar.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

没有任何成功,但它与 UINavigationBar+Image 的完全相同的代码完美配合。

UIToolbar 没有调用drawRect 方法,为什么呢?

I've tried the following:

@implementation UIToolbar (Image)

-(void)drawRect:(CGRect)rect {
    UIImage *img  = [UIImage imageNamed: @"navigationBar.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

Without any success, but it works perfectly with the exact same code for UINavigationBar+Image.

the drawRect method is not getting called for UIToolbar, why is that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枕梦 2024-10-06 20:58:54

我找到了解决方案

对于 UIToolBar,如果您在 UINavigationController 中使用它,您还需要重写 drawLayer:inContext:,因为在导航控制器中使用时,由于某些奇怪的原因,它似乎被用来代替 drawRect: 。

来源:http://atastypixel.com/blog/making- uitoolbar-and-uinavigationbars-background-totally-transparent/

所以我实现了 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CALayer *imgLayer = [[CALayer alloc] init];
    [imgLayer setContents:(id)[[UIImage imageNamed: @"toolbar.png"] CGImage]];
    [imgLayer setBounds:CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height)];
    [imgLayer setPosition:CGPointMake(self.bounds.size.width/2,self.bounds.size.height/2)];
    [layer insertSublayer:imgLayer atIndex:0];
}

I found a solution

For UIToolBar, if you’re using it within a UINavigationController, you’ll want to also override drawLayer:inContext:, as this appears to be used instead of drawRect: when used within a navigation controller, for some weird reason.

Source: http://atastypixel.com/blog/making-uitoolbar-and-uinavigationbars-background-totally-transparent/

So I implemented - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx instead:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    CALayer *imgLayer = [[CALayer alloc] init];
    [imgLayer setContents:(id)[[UIImage imageNamed: @"toolbar.png"] CGImage]];
    [imgLayer setBounds:CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height)];
    [imgLayer setPosition:CGPointMake(self.bounds.size.width/2,self.bounds.size.height/2)];
    [layer insertSublayer:imgLayer atIndex:0];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文