【问题标题】:UIButton style settings are ignored when I override 'drawRect'当我覆盖“drawRect”时,UIButton 样式设置被忽略
【发布时间】:2013-12-11 20:03:55
【问题描述】:

我创建了一个自定义 iOS 数字键盘,其中的按钮带有圆角:

control.layer.cornerRadius = 6;
control.layer.opacity = 1;

在我想要绘制图像的按钮之一上,我将 UIButton 子类化以覆盖“drawRect”函数。

@interface KfKeypadButtonWithDrawing : UIButton

- (void)drawRect:(CGRect)rect;

@end

drawRect 实现只是在按钮上绘制一些线条。没什么特别的。

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    // custom drawing code to create an image on the button
}

但是,一旦我覆盖 drawRect,按钮就不再具有圆角。有什么方法可以在按钮上绘制图像并让按钮尊重cornerRadius 样式设置?

谢谢,

亚伦

【问题讨论】:

    标签: ios objective-c uibutton


    【解决方案1】:

    尝试将您尝试在drawRect 中绘制的内容放入图像(png、jpg)中并使用UIButtons setImage:forStatesetBackgroundImage:forState

    【讨论】:

    • 我们从一张图片开始,但它并不能很好地随着按钮大小的变化而缩放。我们决定转换为使用绘图代码,也就是圆角消失的时候。
    【解决方案2】:

    是的,像这样:

    override func drawRect(rect: CGRect) {
        // the custom drawing
        let roundedRect = UIBezierPath(roundedRect: rect, cornerRadius: 20)
        UIColor.redColor().setFill()
        roundedRect.fill()
    
        // call super
        super.drawRect(rect)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 2016-05-07
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多