设置button的Alignment;button上的文字位置(居左居右)

来源:互联网 发布:sqlserver seq 编辑:程序博客网 时间:2024/06/04 17:49
两种方法:
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(50, 40, 150, 50);    [button setTitle:@"click tap aaa" forState:(UIControlStateNormal)];    button.backgroundColor = [UIColor brownColor];//    button.titleLabel.textAlignment = NSTextAlignmentLeft; //这行代码 无用,没效果//     1    // 设置button 上的内容 在水平方向的 位置(只设置这个的话会紧紧贴着边框)    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;    //可通过设置title的偏移量(距离button上下左右边框的距离)    button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);//     2    button.titleLabel.font = [UIFont systemFontOfSize:17];// 一定要设置button字体的大小,不然宽度计算不对    CGRect btnTextRect = [button.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 15)                                                       options:NSStringDrawingTruncatesLastVisibleLine                                                    attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}                                                       context:nil];    CGFloat btnW = button.frame.size.width;    CGFloat btnTextW = btnTextRect.size.width;    button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, btnW - btnTextW);        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];

1 的效果图


2 的 效果图



0 0
原创粉丝点击