1. 程式人生 > >IOS繼承UIControl封裝自定義UIButton

IOS繼承UIControl封裝自定義UIButton

實現思路,定義一個初始化方法,實現方法是新增一個UIImageView和一個UILabel;

宣告部分:

@interface TabBarItem : UIControl

//自定義初始化方法

- (id)initWithFrame:(CGRect)frame

          imageName:(NSString *)imageName

              title:(NSString *)title;

@end

實現部分:

@implementation TabBarItem

- (id)initWithFrame:(CGRect)frame

          imageName:(NSString *)imageName

              title:(NSString *)title

{

    self = [super initWithFrame:frame];

    if (self) {

     //設定此空間固定大小

        self.width = kScreen_width / 5.0;//5.0是個隨意數字

        self.height = 49;

//建立一個圖片檢視

        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 8, self.width, 20)];

        //

設定圖片

        imageView.image = [UIImage imageNamed:imageName];

//設定圖片的拉伸方式

        imageView.contentMode = UIViewContentModeCenter;

        [self addSubview:imageView];

        [imageView release];

        //建立文字

        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, imageView.bottom + 3

, self.width, 14)];

        label.backgroundColor = [UIColor clearColor];

        label.font = [UIFont systemFontOfSize:12.0];

        label.textColor = [UIColor whiteColor];

        label.textAlignment = NSTextAlignmentCenter;

        label.text = title;

        [self addSubview:label];

        [label release];

    }

returnself;

}