概述
今天在做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文字的对齐方式所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复