以编程方式动态居中并调整UILabel宽度

时间:2015-02-10 14:25:21

标签: ios uilabel

这似乎很简单,但我不能按照我想要的方式工作, 这里有很多类似的问题,但没有解决我的问题。

我使用以下代码设置以超级视图为中心的视图

以两个UILabel作为子视图,也是点数的变化。

NSString *myScoreText = [NSString stringWithFormat:@"My Score: "];
UIFont *myScoreFont = [UIFont boldSystemFontOfSize:14.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:myScoreFont, NSFontAttributeName, nil];
CGFloat myScoreWidth = [myScoreText sizeWithAttributes:attributes].width;

NSString *pointsText = [NSString stringWithFormat:@"%d points", currentScore];
UIFont *pointsFont = [UIFont boldSystemFontOfSize:14.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:pointsFont, NSFontAttributeName, nil];
CGFloat pointsWidth = [pointsText sizeWithAttributes:attributes].width;

CGFloat scoreViewWidth = myScoreWidth + pointsWidth;
UIView *scoreView = [[UIView alloc] initWithFrame:CGRectMake(FRAME_WIDTH/2 - scoreViewWidth/2, elementHeight, scoreViewWidth, LABEL_HEIGHT)];

UILabel *myScoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, myScoreWidth, LABEL_HEIGHT)];
myScoreLabel.font = myScoreFont;
myScoreLabel.text = myScoreText;
myScoreLabel.textAlignment = NSTextAlignmentLeft;

self.pointsLabel = [[UILabel alloc] initWithFrame:CGRectMake(myScoreWidth, 0, pointsWidth, LABEL_HEIGHT)];
self.pointsLabel.textColor = [UIColor redColor];
self.pointsLabel.font = pointsFont;
self.pointsLabel.text = pointsText;
self.pointsLabel.textAlignment = NSTextAlignmentLeft;

[scoreView addSubview:myScoreLabel];
[scoreView addSubview:self.pointsLabel];

显示视图后,当点数在10-99之间时可以正常工作但如果点数增加到100多点,则视图会显示如下文字:My Score: 100 po...而不是My Score: 100 points,当得分为超过1000然后视图显示My Score: 1000 p...,依此类推......

那么我怎样才能正确显示所有文本并保持视图的两个UILabels子视图居中?

由于

1 个答案:

答案 0 :(得分:0)

使用Autolayout:

UILabel *label = [[UILabel alloc]initForAutoLayout];

label.translatesAutoresizingMaskIntoConstraints= NO;


[self.view addSubview:label];

[self.view addConstraint: [NSLayoutConstraint
                                             constraintWithItem:label attribute:NSLayoutAttributeCenterX
                                             relatedBy:NSLayoutRelationEqual toItem:self.view attribute:
                                             NSLayoutAttributeCenterX multiplier:1.0 constant:0.0f]];







 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:label
     attribute:NSLayoutAttributeTop   
     relatedBy:NSLayoutRelationEqual   
toItem:self.view
    attribute:NSLayoutAttributeTop    
   multiplier:1.0     
     constant:100.0]];

label.text = @"a";

使用Purelayout:

添加以下PureLayout库

https://github.com/smileyborg/PureLayout

因为使用Purelayout处理自动布局相对容易。

UILabel *label = [[UILabel alloc]initForAutoLayout];

[scoreView addSubview:label];

[label autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0.0f];

[label autoAlignAxisToSuperviewAxis:ALAxisVertical];

[label setText:@"hello"];

使用ALAxisVertical对文本进行居中,也可以使用ALAxisHorizo​​ntal使其水平居中。