原生UIButton創(chuàng)建:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 150, 50);
button.backgroundColor = [UIColor yellowColor];
// 注意:下面這種方式設(shè)置按鈕文字沒(méi)有效果
// button.titleLabel.text = @"普通按鈕";
[button setTitle:@"普通按鈕" forState:UIControlStateNormal];
button.titleLabel.backgroundColor = [UIColor purpleColor];
[button setImage:[UIImage imageNamed:@"miniplayer_btn_playlist_normal"] forState:UIControlStateNormal];
// 注意:下面這種方式設(shè)置按鈕文字沒(méi)有效果
// button.imageView.image = [UIImage imageNamed:@"miniplayer_btn_playlist_normal"];
button.imageView.backgroundColor = [UIColor grayColor];
[self.view addSubview:button];
}
-
效果:
Snip20160823_4.png
自定義Button
- 創(chuàng)建一個(gè)LHLUIButton類(lèi)吵瞻,繼承UIButton
Snip20160823_5.png
- .m文件中
// 方法一:重寫(xiě)下面兩個(gè)方法 重新設(shè)置子控件的frame
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
return CGRectMake(0, 0, 100, 50);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect{
return CGRectMake(100, 0, 50, 50);
}
- 在ViewController中導(dǎo)入LHLUIButton亚茬,用LHLUIButton創(chuàng)建按鈕
#import "ViewController.h"
#import "LHLButton.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LHLButton *button = [LHLButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 150, 50);
button.backgroundColor = [UIColor yellowColor];
// 注意:下面這種方式設(shè)置按鈕文字沒(méi)有效果
// button.titleLabel.text = @"普通按鈕";
[button setTitle:@"普通按鈕" forState:UIControlStateNormal];
button.titleLabel.backgroundColor = [UIColor purpleColor];
[button setImage:[UIImage imageNamed:@"miniplayer_btn_playlist_normal"] forState:UIControlStateNormal];
// 注意:下面這種方式設(shè)置按鈕文字沒(méi)有效果
// button.imageView.image = [UIImage imageNamed:@"miniplayer_btn_playlist_normal"];
button.imageView.backgroundColor = [UIColor grayColor];
[self.view addSubview:button];
}
-
效果圖:
Snip20160823_6.png 重寫(xiě)initWithFrame方法鼎兽,設(shè)置子控件屬性
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
// 文本居中
self.titleLabel.textAlignment = NSTextAlignmentCenter;
// 改變圖片的內(nèi)容模式
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
}
return self;
}
- 也可重寫(xiě)layoutSubViews設(shè)置子控件的frame
// 方法二
- (void)layoutSubviews{
// 注意:這里一定要調(diào)用父類(lèi)的方法7簟E玳埂L!徙瓶!
[super layoutSubviews];
self.titleLabel.frame = CGRectMake(0, 0, 100, 50);
self.imageView.frame = CGRectMake(100, 0, 50, 50);
}
- 設(shè)置按鈕的邊距
- (void)viewDidLoad {
[super viewDidLoad];
// 設(shè)置按鈕的內(nèi)邊距
//1.設(shè)置內(nèi)容
// self.button.contentEdgeInsets = UIEdgeInsetsMake(-20, 0, 0, 0);
// 2.設(shè)置圖片
self.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
// 3.設(shè)置標(biāo)題
self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
}