iOS开发相关---UIButton容易忘记的方法

使用

button.titleLabel.textAlignment = NSTextAlignmentLeft; 这行代码是没有效果的,这只是让标签中的文本左对齐,但

并没有改变标签在按钮中的对齐方式。


所以,我们首先要使用

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 这行代码,把按钮的内容(控件)

的对齐方式修改为水平左对齐,但是这们会紧紧靠着左边,不好看,

所以我们还可以修改属性:

button.titleEdgeInsets = UIEdgeInsetsMake(01000);

这行代码可以让按钮的内容(控件)距离左边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];

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值