创建uibutton子类

pro*_*ock 6 iphone objective-c

我试图将UIButton子类化为包含一个活动指示符,但是当我使用initWithFrame :(因为我是uibutton的子类我没有使用buttonWithType :)按钮不显示.在这种情况下我如何设置按钮类型?:

我的视图控制器:

    ActivityIndicatorButton *button = [[ActivityIndicatorButton alloc] initWithFrame:CGRectMake(10, 10, 300, 44)];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Older Posts..." forState: UIControlStateNormal];
    [cell addSubview:button];
    [button release];
Run Code Online (Sandbox Code Playgroud)

我的activityindicatorbutton类:

#import <Foundation/Foundation.h>


@interface ActivityIndicatorButton : UIButton {

    UIActivityIndicatorView *_activityView;
}

-(void)startAnimating;
-(void)stopAnimating;
@end

@implementation ActivityIndicatorButton

- (id)initWithFrame:(CGRect)frame {
    if (self=[super initWithFrame:frame]) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityView.frame = CGRectOffset(_activityView.frame, 60.0f, 10.0f);

        [self addSubview: _activityView];
    }
    return self;
}

-(void) dealloc{
    [super dealloc];
    [_activityView release];
    _activityView = nil;
}

-(void)startAnimating {
    [_activityView startAnimating];
}

-(void)stopAnimating {
    [_activityView stopAnimating];
}
@end
Run Code Online (Sandbox Code Playgroud)

ban*_*isa 10

赞成合成而不是继承.

创建一个包含所需组件的UIView,并将它们添加到视图中.


jms*_*617 5

我遇到了类似的情况,并同意杰夫的说法,你真的不需要继承UIButton.我通过继承UIControl来解决这个问题,然后重写layoutSubviews来完成我想要的"按钮"视图的所有配置.这是一个更简单的实现,它继承了UIButton,因为似乎有一些隐藏的mojo在幕后进行.我的实现看起来像这样:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    self.opaque = YES;

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:self.imageView];

    self.textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:self.textLabel];
    }

return self;
}
Run Code Online (Sandbox Code Playgroud)

layoutSubviews看起来像这样:

- (void)layoutSubviews {
[super layoutSubviews];

// Get the size of the button
CGRect bounds = self.bounds;

// Configure the subviews of the "button"
...
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*ley -2

您确实不想\xe2\x80\x99t 子类化UIButton. 它\xe2\x80\x99是一个类簇,因此各个实例将类似于UIRoundRectButton或其他一些私有Apple类。您想要做什么需要子类?

\n

  • UIButton 根本不是一个类簇。类簇由公共抽象类表示,这意味着没有实例变量,并且具有一堆私有具体子类,这些子类提供抽象类的抽象方法的实现。另一方面,UIButton 是一个具体的类,它的方法都不是抽象的,并且它具有实例变量来存储您通过其参数传递的值。唯一有问题的部分是 +buttonWithType 可以实例化子类而不是直接实例化 UIButton,因此它可以被视为工厂方法,而不是类簇...... (68认同)
  • 要添加 @Psycho 的注释,请参阅 `buttonWithType:` 文档: _This 方法是一个方便的构造函数,用于创建具有特定配置的按钮对象。如果您子类化 UIButton,则此方法不会返回子类的实例。如果要创建特定子类的实例,则必须直接分配/初始化按钮。_ (4认同)