【问题标题】:NSTextAlignmentJustified to UILable textAligment on iOS6 will crashNSTextAlignment Justified to UILabel text Alignment on iOS6 会崩溃
【发布时间】:2012-12-06 12:37:03
【问题描述】:

我现在用的是Xcode4.5和iOS6,iOS6已经改变了UILable的textAlignment,

label.textAlignment = NSTextAlignmentJustified;

代码将在带有 ios6 SDK 的 iPhone 6.0 Simulator 上崩溃。但不会在带有 iOS6 SDK 的 iPhone 5.0 模拟器上崩溃。

iOS6支持NSTextAlignmentJustified,但是为什么会崩溃?

【问题讨论】:

  • 你能发布什么异常吗?
  • 同样的错误。错误日志是:*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'textAlignment does not accept NSTextAlignmentJustified'

标签: ios6 uilabel text-alignment


【解决方案1】:

编辑 1:

使用NSAttributedString 我们可以证明文本的合理性。

NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
paragraphStyles.alignment                = NSTextAlignmentJustified;
paragraphStyles.firstLineHeadIndent      = 0.05;    // Very IMP

NSString *stringTojustify                = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";
NSDictionary *attributes                 = @{NSParagraphStyleAttributeName: paragraphStyles};
NSAttributedString *attributedString     = [[NSAttributedString alloc] initWithString:stringTojustify attributes:attributes];

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

UITextAlignmentJustify 已弃用,在 iOS 6 下不再可用。

SO link 也提供了所有可能的对齐文本解决方案 看看this pageiOS6 prerelease Documentation

【讨论】:

  • NSAttributedString 没有方法 setTextAlignment:lineBreakMode:。该方法是第三方 UILabel 子类的一部分。
  • 实际上设置 firstLineHeadIndent 属性是阻止 uilabel 调整字体大小以适应边界的能力。您需要设置的是 headIndent 或 trailIndent 属性,或者在此处插入 poloDelaVega 所指向的 NSBaselineOffsetAttributeName 属性
【解决方案2】:

我找到了一种在 iOS 7 中设置标签 Justifiy 的方法:我只需将 NSBaselineOffsetAttributeName 设置为 0。

不知道为什么需要在 iOS 7 上添加此基线设置(它在 iOS 6 上运行良好)。

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSTextAlignmentJustified;

NSDictionary *attributes = @{ NSParagraphStyleAttributeName : paragraph,
                                        NSFontAttributeName : self.textLabel.font,
                              NSBaselineOffsetAttributeName : [NSNumber numberWithFloat:0] };

NSAttributedString *str = [[NSAttributedString alloc] initWithString:content 
                                                          attributes:attributes];

self.textLabel.attributedText = str;

希望有所帮助;)

【讨论】:

  • 非常好!!!正常运行。可以将NSBaselineOffsetAttributeName : [NSNumber numberWithFloat:0]换成NSBaselineOffsetAttributeName : @0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多