The problem and solution that the right space cannot be displayed in UILabel in iOS development

Problem Description:

  • The effect you want to achieve: UILabel is adaptive to the width, the text is displayed in the center, and the text has a fixed distance from the left and right sides (note: only one line of text is displayed).
  • The problem encountered: I wanted to be lazy at first, directly add two spaces before and after the text to be displayed, and then display the text in the center. However, the display effect of this method is: the space before the text can be displayed normally, the space after the text will be automatically removed, and the resulting text will be displayed on the right.

Solution:

  • Use below method to get text width
#pragma mark 获取文本宽度
- (CGFloat)getWidthWithText:(NSString *)text withFont:(UIFont *)font {
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:font}];
    return size.width;
}
  • Then update the frame of UILabel
Note: Since this method is relatively simple, no specific code will be provided. If you have any questions or have better solutions, please comment and leave a message below.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326292593&siteId=291194637