iOS7中的NSTextAlignmentJustified无法正常工作。

12
我有一个应用程序,它使用NSTextAlignmentJustified来处理NSAttributedString。在iOS 6中一切正常。但是在iOS 7(模拟器或设备都没有区别)中,没有显示对齐。此外,行间距从iOS 67似乎发生了巨大变化。其他人是否遇到过这个问题?有没有办法在iOS 7中创建一个文本块,使其能够像在iOS 6中一样正常工作? 问候,马库斯

我也发现了UILabel的这个问题。我会更深入地研究它,因为我真的希望我的文本对齐! - Rambatino
3个回答

27

好的,我找到了一种方法来使标签在iOS 7中对齐:只需将NSBaselineOffsetAttributeName设置为0即可。

不知道为什么它有效,但它确实有效。

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentJustified;

NSAttributedString *string = [[NSAttributedString alloc] initWithString:rawString 
          attributes:[NSDictionary dictionaryWithObjectsAndKeys:
          paragraphStyle, NSParagraphStyleAttributeName , 
          [NSNumber numberWithFloat:0],NSBaselineOffsetAttributeName, 
          nil]];

我以为NSBaselineOffsetAttributeName在iOS 6中已经被弃用了?https://developer.apple.com/LIBRARY/ios/releasenotes/General/RN-iOSSDK-6_0/index.html由于兼容性问题,NSBaselineOffsetAttributeName属性在iOS 6中不再受支持。 - Sean Dunford
它并没有被弃用!https://developer.apple.com/reference/uikit/nsbaselineoffsetattributename - Bisca

8

NSMutableParagraphStyle上设置firstLineHeadIndent也可以起作用。

NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
paragraphStyles.alignment                = NSTextAlignmentJustified;    // To justified text
paragraphStyles.firstLineHeadIndent      = 0.05;    // IMP: must have a value to make it work

NSString *stringTojustify                = @"No one wakes up excited to see more advertising, no one goes to sleep thinking about the ads they’ll see tomorrow.";
NSDictionary *attributes                 = @{NSParagraphStyleAttributeName: paragraphStyles};
NSAttributedString *attributedString     = [[NSAttributedString alloc] initWithString:stringTojustify attributes:attributes];

self.lblQuote.attributedText             = attributedString;
self.lblQuote.numberOfLines              = 0;
[self.lblQuote sizeToFit];

是的!在iOS 9上添加firstLineHeadIndent可以使我的文本对齐。谢谢! - Fjohn

1
只是为了记录,对于普通的UILabel,你也可以在第一个字符处添加'\n'。
        self.text = [NSString stringWithFormat:@"\n%@",TextString];
        {
            CurFrame.origin.y -= FontSize;
            self.frame = CurFrame;
        }
        self.textAlignment = NSTextAlignmentJustified;

不错,但是有没有一种方法可以避免初始空行而不切换到NSAttributedString? - Cœur
1
据我所知,\f(分页符)可以在不调整框架大小的情况下干净地完成,但这仍然是一种hack。如果您需要对齐文本,那么学习NSAttributedString的工作原理肯定是值得努力的,因为迟早您会需要它们,而且苹果可能会在某个时候更改行为(这完全取决于代码背后实际做了什么来使这个东西起作用,但我无意去检查)。 - Lord Kale XI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接