使用
button.titleLabel.textAlignment = NSTextAlignmentLeft; 这行代码是没有效果的,这只是让标签中的文本左对齐,但
并没有改变标签在按钮中的对齐方式。
所以,我们首先要使用
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 这行代码,把按钮的内容(控件)
的对齐方式修改为水平左对齐,但是这们会紧紧靠着左边,不好看,
所以我们还可以修改属性:
button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
这行代码可以让按钮的内容(控件)距离左边10个像素,这样就好看多了
UIButton根据内容设置尺寸
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(150, 100, 20, 20)];
[btn setBackgroundColor:[UIColor blackColor]];
NSString *str = @"高度不变获取宽度";
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
CGSize size = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, btn.frame.size.height) options:NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
//根据计算结果重新设置UILabel的尺寸
[btn setFrame:CGRectMake(150, 100, size.width + 50, 20)];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn setTitle:str forState:UIControlStateNormal];
[self.view addSubview:btn];
UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(150, 100, 20, 20)];
[btn1 setBackgroundColor:[UIColor redColor]];
NSString *str1 = @"高度宽度";
NSDictionary *attribute1 = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
CGSize size1 = [str1 boundingRectWithSize:CGSizeMake(MAXFLOAT, btn1.frame.size.height) options:NSStringDrawingTruncatesLastVisibleLine attributes:attribute1 context:nil].size;
NSLog(@"size1.width=%f, size1.height=%f", size1.width, size1.height);
[btn1 setFrame:CGRectMake(150, 150, size1.width + 50, 20)];
[btn1 setTitle:str1 forState:UIControlStateNormal];
[btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self.view addSubview:btn1];
}