UIButton文字的对齐方式

今天在做UIButton的title对齐方式时,以个人以往的经验来做首先想到的是

@property(nonatomic,readonly,retain) NSAttributedString *currentAttributedTitle

UIButton的固有的AttibuteTitle方法可以改变文字的字体样式,当时字体的对齐方式确无法更改。

代码如下

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *testBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    testBtn.frame = CGRectMake(100, 200, 120, 60);
    testBtn.backgroundColor = [UIColor lightGrayColor];
    [testBtn setTitle:@"测试" forState:UIControlStateNormal];
    [testBtn setAttributedTitle:[self titleAttr] forState:UIControlStateNormal];
    [testBtn addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchDragInside];
    [self.view addSubview:testBtn];
    // Do any additional setup after loading the view, typically from a nib.
}

- (NSAttributedString *)titleAttr
{
    NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];
    [ps setAlignment:NSTextAlignmentLeft];
    NSDictionary *attribs = @{NSParagraphStyleAttributeName:ps};
    NSAttributedString  *attriString = [[ NSAttributedString alloc] initWithString:@"测试" attributes:attribs];
    return  attriString;
}

测试之后无法改变文字的对齐方式,但是这种方法对于展示文字的UILabel可以改变文字的对齐方式。

纠结了半天终于在网上看到了一个方法

@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment; 

该方法属于UIControl
UIButton 继承于UIControl

文档的解释为

//*

这个属性主要是用于设置你自定义的这个空间里面的text or image在水平方向上的位置。

*/

也可以设置title的偏移量

@property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; /


在解决这个问题的时候还发现了一个Button的一个属性titleLabel,这个是

@property(nonatomic,readonly,retain) UILabel     *titleLabel
是一个只读的属性,虽然是只读的属性但是给此属性赋值时编译器不报错。大家要小心一下。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值