1.自定义按钮
//
// TitleButton.h
// 自定义文字在左图片在右的按钮
#import <UIKit/UIKit.h>
@interface TitleButton : UIButton
@end
//
// TitleButton.m
#import "TitleButton.h"
@implementation TitleButton
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 图片内容模式:居中
self.imageView.contentMode = UIViewContentModeCenter;
[self setImage:[UIImage imageNamed:@"nav_screening_down_normal"] forState:UIControlStateNormal];
[self setImage:[UIImage imageNamed:@"nav_screening_down_pressed"] forState:UIControlStateHighlighted];
[self setImage:[UIImage imageNamed:@"nav_screening_up_normal"] forState:UIControlStateSelected];
// 文字颜色
[self setTitleColor:[UIColor colorWithRed:251/255.0 green:85/255.0 blue:8/255.0 alpha:1.0] forState:UIControlStateNormal];
// 文字大小
self.titleLabel.font = [UIFont systemFontOfSize:14];
// 文字居中对齐
self.titleLabel.textAlignment = NSTextAlignmentRight;
}
return self;
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleW = contentRect.size.width - 11 - 5;
CGFloat titleH = contentRect.size.height;
return CGRectMake(0, 0, titleW, titleH);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW = 11;
CGFloat imageH = contentRect.size.height;
CGFloat imageX = contentRect.size.width - imageW;
return CGRectMake(imageX, 0, imageW, imageH);
}
@end
2.使用
TitleButton *navRight = [[TitleButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
[navRight setTitle:@"北京" forState:UIControlStateNormal];