扩展UIButton for iOS的问题

时间:2011-05-23 23:24:17

标签: uibutton subclass

我尝试扩展UIButton,但我在ColorButton的实现文件的初始化程序中不断获得“EXC_BAD_ACCESS”。

ColorButton的标题。

#import <Foundation/Foundation.h>


@interface ColorButton : UIButton {
    UIImage * originalImage;
}

@property (nonatomic,readonly) NSString * buttonName;

-(id) initButtonWithName:(NSString *) color;
-(void) setOriginalImage;
-(void) setImage:(UIImage *) image;
@end

ColorButton实施

#import "ColorButton.h"

@implementation ColorButton

@synthesize buttonName;

-(id) initButtonWithName:(NSString *) color {
    if ((self = (ColorButton *)[UIButton buttonWithType:UIButtonTypeCustom])) {
        buttonName = color;
        [self setTitle:buttonName forState:UIControlStateNormal]; //This is the line of the "EXC_BAD_ACCESS" error.
        [self setBackgroundImage:[self backgroundImageForDevice:color] forState:UIControlStateNormal]; // This line gets the error too. If I comment the line before it out.
    }
    return self;
}

-(UIImage *) backgroundImageForDevice:(NSString *) color {
        color = [color stringByAppendingString:@"Bubble"];
    if ([[[UIDevice currentDevice] model] isEqualToString:@"iPad"] ||[[[UIDevice currentDevice] model] isEqualToString:@"iPad Simulator"]) {
        color = [color stringByAppendingString:@"-iPad"];
    }
    color = [color stringByAppendingString:@".png"];
    return [UIImage imageNamed:color];
}

-(void) setOriginalImage {
    [self setBackgroundImage:originalImage forState:UIControlStateNormal];
}

-(void) setImage:(UIImage *) image {
    [self setImage:image forState:UIControlStateNormal];
}
@end

1 个答案:

答案 0 :(得分:2)

您无法将UIButton *个实例投射到ColorButton *类型。

您必须记住ColorButton继承自UIButton而不是其他方式,这意味着ColorButton的每个实例都是UIButton的定义,但是反之亦然。

这是另一个具有完全相同问题的帖子:)

objective C: Buttons created from subclass of UIButton class not working