简体   繁体   中英

UILabel not showing centre align in ios

I am having one problem stuck. I have created UILabel and changed it frame ie size height as per the content and it is very fine with all the iPhone devices. However my label is not centre align if we are getting just few word, like Adidas, Nike etc.

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];

Add following line of code at the end after setting the frame.

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

Try with this.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM