UIButton *searchButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
UIImage *searchImage = [UIImageimageNamed:@"searchBarBg.png"];
searchButton.frame =CGRectMake(10, 10, searchImage.size.width, searchImage.size.height);
[searchButtonsetBackgroundImage:searchImage forState:UIControlStateNormal];
[searchButtonsetTitle:@"1111"forState:UIControlStateNormal];
[searchButton setTitleColor:[UIColorredColor] forState:UIControlStateNormal];
[searchButton.titleLabel setFont:[UIFont systemFontOfSize:12.0f]];
searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;//默认居中
/*
typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
UIControlContentHorizontalAlignmentCenter = 0,
UIControlContentHorizontalAlignmentLeft = 1,
UIControlContentHorizontalAlignmentRight = 2,
UIControlContentHorizontalAlignmentFill = 3,
};
*/
有些时候我们想让UIButton的title居左对齐,我们设置
searchButton.textLabel.textAlignment = UITextAlignmentLeft
是没有作用的,我们需要设置
searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
此时文字会紧贴到左边框,我们可以设置
searchButton.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
使文字距离左边框保持10个像素的距离。
/*
UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
*/
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
不能用
- (void)setImage:(UIImage *)image forState:(UIControlState)state;
这样就可以同时显示图片和文字了。