对齐UIButton的文本?

时间:2013-03-07 11:27:25

标签: iphone objective-c xcode uibutton

我正在生成一些按钮。在按钮中,我显示日期和用户给出的引用ID。我希望这些数据在按钮中保持对齐。

我尝试过:

[button.titleLabel setTextAlignment:UITextAlignmentLeft]; 
button.titleLabel.textAlignment = UITextAlignmentLeft;

但这不起作用。

 - (void)viewDidLoad
{
 [super viewDidLoad];
 [scrollView setScrollEnabled:YES];
 [scrollView setContentSize:CGSizeMake(320, 500)];

int i = 0;

for (CalculatorData *data in calcDatas) {

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];


    button.frame = CGRectMake(1 , 20 + i*40, 295, 30);

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy HH:MM:SS"];

    NSString *dateString = [dateFormat stringFromDate:data.updateDate];

    NSString *title = [NSString stringWithFormat:@"%@ : %@",dateString,[data dataKey]];


    [button setTitle:title forState:UIControlStateNormal];


    [button addTarget:self action:@selector(buttonPressed:)
    forControlEvents:UIControlEventTouchUpInside];
    button.tag = data.calcId;


    [scrollView addSubview:button];
    i++;
}

8 个答案:

答案 0 :(得分:34)

您可以使用contentHorizontalAlignment

  

“内容(文本或图像)的水平对齐方式   接收器“。

contentVerticalAlignment属性:

  

“内容(文本或图像)的垂直对齐方式   接收器“。

使用示例:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

答案 1 :(得分:8)

使用此:

button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill; 


button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

答案 2 :(得分:2)

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

答案 3 :(得分:1)

enter image description here

在故事板中查看Content-Alignment Vertical

答案 4 :(得分:1)

对于Swift 3,以下内容对我有用:

button.contentHorizontalAlignment = .left
button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)

答案 5 :(得分:0)

button.titleLabel.textAlignment = NSTextAlignmentLeft;

答案 6 :(得分:0)

在Swift中你可以使用它:

uibutton / uilabel.titleLabel?.textAlignment = .Center

NSTextAlignment是一个枚举,你可以通过放置.VALUE来分配它。

以下是可能的对齐枚举 case Left //视觉上左对齐

case Center // Visually centered
case Right // Visually right aligned
/* !TARGET_OS_IPHONE */
// Visually right aligned
// Visually centered

case Justified // Fully-justified. The last line in a paragraph is natural-aligned.
case Natural // Indicates the default alignment for script

答案 7 :(得分:0)

Swift 3.x:

button.titleLabel?.textAlignment = .center