2015-02-10 2 views
0

Кажется, что-то простое, но я не могу заставить его работать так, как я этого хочу, есть много похожих вопросов, но не из них решена моя проблема.Динамически центрировать и регулировать ширину UILabel программно

Я использую следующий код, чтобы установить вид центрированный в надтаблицах

с два UILabels как подвиды, а также количеством точек изменения.

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 с центром?

Благодаря

+0

Вам нужно решение, используя автозапуск? – YaBoiSandeep

+0

Мне нужно решение, которое может быть достигнуто программно (без раскадровки или xibs), если я могу использовать автозапуск таким образом, то да –

ответ

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

как это относительно легко справиться с autolayout использованием Purelayout ,

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

[scoreView addSubview:label]; 

[label autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0.0f]; 

[label autoAlignAxisToSuperviewAxis:ALAxisVertical]; 

[label setText:@"hello"]; 

текст центрируется с помощью ALAxisVertical, также вы можете центрировать его по горизонтали с помощью ALAxisHorizontal.

+0

Спасибо за ваше время и помощь, но я искал решение без внешних библиотек –

+0

проверить обновленный ответ с автозапуском – YaBoiSandeep

Смежные вопросы