gpt4 book ai didi

iphone - 在 UILabel iOS 中对齐文本

转载 作者:行者123 更新时间:2023-12-03 18:23:06 24 4
gpt4 key购买 nike

我遇到一个问题,在 iOS 中我使用 UILabel 显示 2,3 行文本,我想将文本对齐,但我没有找到任何选项来这样做。有什么建议如何使标签中的文本对齐吗?

我把这些行放在从顶部开始

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *textString = someString;
UIFont *textFont = [UIFont fontWithName:@"Futura" size:14];
CGSize textStringSize = [textString sizeWithFont:textFont
constrainedToSize:maximumSize
lineBreakMode:text.lineBreakMode];

CGRect textFrame = CGRectMake(10, 110, 300, textStringSize.height);
text.frame = textFrame;

所以像这样的技巧可以让它变得合理谢谢

最佳答案

自 iOS6 以来,现在有一种方便的方法来对齐文本。您可以创建 NSAttributedString 的实例,设置适当的属性并将此属性字符串分配给表示 View 的文本,例如 UILabel、UITextView 等。这很简单:

  1. 创建 NSMutableParagraphStyle 的实例并设置其属性。

    NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
    paragraphStyles.alignment = NSTextAlignmentJustified; //justified text
    paragraphStyles.firstLineHeadIndent = 10.0; //must have a value to make it work
  2. 为文本属性创建 NSDictionary 并创建属性字符串。

    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles};
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: string attributes: attributes];
  3. 将属性字符串设置为标签。

    existingLabel.attributedText = attributedString;

关于iphone - 在 UILabel iOS 中对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7145969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com