12

我正在生成一些按钮。在按钮中,我显示日期和用户提供的参考 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++;
}
4

8 回答 8

35

您可以使用contentHorizo​​ntalAlignment

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

contentVerticalAlignment属性:

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

示例用法:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
于 2013-03-07T11:29:31.267 回答
8

用这个 :

button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill; 


button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
于 2013-03-07T11:34:56.057 回答
2
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
于 2013-03-07T11:31:01.790 回答
1

在此处输入图像描述

查看情节提要中的 Content-Alignment Vertical

于 2016-11-07T15:50:13.310 回答
1

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

button.contentHorizontalAlignment = .left
button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)
于 2017-09-30T23:12:06.280 回答
0

button.titleLabel.textAlignment = NSTextAlignmentLeft;

于 2013-03-07T11:55:35.663 回答
0

在 Swift 中,你可以使用这个:

uibutton/uilabel.titleLabel?.textAlignment = .Center

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

这是可能的对齐枚举的情况左//视觉左对齐

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
于 2015-09-09T18:22:51.093 回答
0

斯威夫特 3.x:

button.titleLabel?.textAlignment = .center
于 2017-07-24T18:28:11.557 回答