代码之家  ›  专栏  ›  技术社区  ›  0xced

从nib加载的UIButton子类未正确初始化

  •  4
  • 0xced  · 技术社区  · 14 年前

    我有一个非常简单的UIButton子类:

    @interface MyButton : UIButton
    @end
    
    @implementation MyButton
    
    - (id) initWithCoder:(NSCoder *)decoder
    {
        if (!(self = [super initWithCoder:decoder]))
            return nil;
    
        NSLog(@"-[%@ initWithCoder:%@]", self, decoder);
    
        return self;
    }
    
    @end
    

    在Interface Builder中,我添加了一个UIButton,将其按钮类型设置为 圆形矩形 以及它的阶级身份 MyButton .

    -[<MyButton: 0x5b23970; baseClass = UIButton; frame = (103 242; 114 37); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x5b23a90>> initWithCoder:<UINibDecoder: 0x6819200>]
    

    但是这个按钮不再是圆形的矩形按钮了。

    在iOS 3.2和iOS 4上都可以观察到。

    不是可以接受的答案,谢谢。

    2 回复  |  直到 14 年前
        1
  •  4
  •   Community CDub    8 年前

    以编程方式,您可以用 +[UIButton buttonWithType:] UIRoundedRectButton )但是从一个泛型按钮类。但是你不能从 UIRoundedRect按钮 因为它是一个内部类。

    从UIButton派生似乎有问题,我看到很多人建议从UIControl派生并自己实现绘图。

    但你可能会发现这些文章很有帮助:

    How to override -drawrect in UIButton subclass?

    http://www.cocoabuilder.com/archive/cocoa/284622-how-to-subclass-uibutton.html

    http://www.cimgf.com/2010/01/28/fun-with-uibuttons-and-core-animation-layers/

    另外,我不知道为什么要从UIButton派生,但是如果要进行一些不涉及覆盖任何其他方法的自定义,那么可以使用这样一个事实:

    - (id)initWithCoder:(NSCoder *)decoder {
       // Decode the frame
       CGRect decodedFrame = ...;
       [self release];
       self = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       [self setFrame:decodedFrame];
       // Do the custom setup to the button
       return self;
    }
    
        2
  •  0
  •   Rob Rix    14 年前

    -awakeFromNib 而不是 -initWithCoder: