我是靠谱客的博主 笨笨火车,这篇文章主要介绍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
是一个只读的属性,虽然是只读的属性但是给此属性赋值时编译器不报错。大家要小心一下。



最后

以上就是笨笨火车最近收集整理的关于UIButton文字的对齐方式的全部内容,更多相关UIButton文字内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部