那种带箭头的排序按钮

效果就像下边这样▼


那种带箭头的排序按钮_第1张图片
屏幕快照 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];
}
那种带箭头的排序按钮_第2张图片
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];
}

你可能感兴趣的:(那种带箭头的排序按钮)