遇到个需求效果如下:
然后开始进行思考,这里实现的方式有很多种,我一我就不一一列举了,我这里就提供一个方法
这个方法是通过修改button的titleEdgeInsets和button的imageEdgeInsets代码如下:
- (UIButton *)createButtonWithTitle:(NSString *)title{
// 创建标题按钮
UIButton * button = [[UIButton alloc] init];
button.imageView.contentMode = UIViewContentModeScaleAspectFit;
[button setImage:[UIImage imageNamed:@"login_selected_normal"] forState:UIControlStateNormal];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button sizeToFit];
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width - button.frame.size.width + button.titleLabel.frame.size.width, 0, 0);
button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.titleLabel.frame.size.width - button.frame.size.width + button.imageView.frame.size.width);
[button addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
然后我们观察小修改后的效果: