效果就像下邊這樣▼
屏幕快照 2016-08-08 下午5.56.00.png
對于實現這種效果的思路就是改變UIButton的TitleEdgeInsets與ImageEdgeInsets這兩個屬性的值就好了。
?就是改變一下titleLabel與imageView的frame.
實現的關鍵代碼如下
- (void) setImage:(UIImage *)image withTitle:(NSString *)title forState:(UIControlState)stateType {
[self setTitleEdgeInsets:UIEdgeInsetsMake(3, -12, 3, 12)];
self.titleLabel.font = [UIFont systemFontOfSize:14];
self.titleLabel.numberOfLines = 0;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
CGRect rect = self.bounds;
CGFloat x = CGRectGetMaxX(rect);
[self setImageEdgeInsets:UIEdgeInsetsMake(3, x - 11, 3, 3)];
[self setImage:image forState:UIControlStateNormal];
[self setTitle:title forState:UIControlStateNormal];
}
8F259523-1CC3-4EA1-913B-1CEA49ED4152.png
這個方法是寫在一個繼承自UIButton的子類里的。以后直接創建一個這種類型的按鈕就行了。
然后在使用的時候▼
@property (weak, nonatomic) IBOutlet ButtonSetImageRight *testBtn;
- (void)viewDidLoad {
[super viewDidLoad];
ButtonSetImageRight *button = [ButtonSetImageRight buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 200, 130, 40);
button.layer.borderColor = [UIColor grayColor].CGColor;
button.layer.borderWidth = 1;
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"arrow"] withTitle:@"測試一下能顯示多少字" forState:UIControlStateNormal];
[_testBtn setImage:[UIImage imageNamed:@"arrow"] withTitle:@"我就試試能顯示多少字" forState:UIControlStateNormal];
_testBtn.layer.borderWidth = 1;
[self.view addSubview:button];
}