2013年3月12日 星期二

Custom UIButton 自定義按鈕

宣告一個自定義的Button, 賦予位置, 大小, 設置圓角, 以及按下後執行的method
CGRect rect = CGRectMake(86,252,148,44);
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:rect];
[btn addTarget:self action:@selector(btnPress:) forControlEvents:UIControlEventTouchUpInside];
[btn.layer setMasksToBounds:YES];
[btn.layer setCornerRadius:10.0f];

按鈕未按下外觀(文字, 文字顏色 背景顏色)
[btn setTitle:@"Normal" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setBackgroundImage:[self imageColorWithUIColor:[UIColor yellowColor]] forState:UIControlStateNormal];

按鈕按下外觀(文字, 文字顏色 背景顏色)
[btn setTitle:@"Highlighted" forState:UIControlStateHighlighted];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[btn setBackgroundImage:[self imageColorWithUIColor:[UIColor blueColor]] forState:UIControlStateHighlighted];

背景顏色方法實作(使用UIColor建立一個UIImage)
- (UIImage *)imageColorWithUIColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

沒有留言:

張貼留言