UILabel 在 ios 中未显示居中对齐

UILabel not showing centre align in ios

我遇到了一个问题。我已经创建了 UILabel 并根据内容更改了它的框架,即大小高度,并且它对所有 iPhone 设备都很好。然而,如果我们只得到几个词,比如阿迪达斯、耐克等,我的标签就不会居中对齐

brandtitlelabel = [[UILabel alloc] init];
brandtitlelabel.backgroundColor = [UIColor clearColor];
brandtitlelabel.textColor = [UIColor commonTextColor];
brandtitlelabel.numberOfLines = 0;
brandtitlelabel.adjustsFontSizeToFitWidth = YES;
brandtitlelabel.minimumScaleFactor = 0.1;
brandtitlelabel.textAlignment = NSTextAlignmentCenter;
brandtitlelabel.lineBreakMode = NSLineBreakByWordWrapping;
brandtitlelabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:30];

NSString *text = @"Adidas";
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:brandtitlelabel.font}];
rect = [attributedText boundingRectWithSize:(CGSize){self.view.frame.size.width, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
rect.origin = CGPointMake(0, 66);
brandtitlelabel.frame = rect;
brandtitlelabel.text = text;
[self.view addSubview:brandtitlelabel];

设置框架后在末尾添加如下代码

brandtitlelabel.textAlignment = NSTextAlignmentCenter;
brandtitlelabel.lineBreakMode = NSLineBreakByWordWrapping;

试试这个。

brandtitlelabel.text = text;
brandtitlelabel.center = CGPointMake(self.view.center.x,brandtitlelabel.center.y);//replace an 'self.view' with your 'superver' on which you want to center.
[self.view addSubview:brandtitlelabel];