【问题标题】:align text using drawInRect:withAttributes:使用 drawInRect:withAttributes 对齐文本:
【发布时间】:2013-09-27 16:42:06
【问题描述】:

在我的应用程序的 iOS 5 版本中:

[self.text drawInRect: stringRect
             withFont: [UIFont fontWithName: @"Courier" size: kCellFontSize]
        lineBreakMode: NSLineBreakByTruncatingTail
            alignment: NSTextAlignmentRight];

我正在升级 iOS 7。不推荐使用上述方法。我现在使用 drawInRect:withAttributes:attributes 参数是一个 NSDictionary 对象。我可以使用 drawInRect:withAttributes: 为前一个 font 参数工作:

      UIFont *font = [UIFont fontWithName: @"Courier" size: kCellFontSize];

      NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName,
                                  nil];

      [self.text drawInRect: stringRect
             withAttributes: dictionary];

我要向 dictionary 添加哪些键值对来获得 NSLineBreakByTruncatingTailNSTextAlignmentRight

【问题讨论】:

    标签: ios nsstring ios7


    【解决方案1】:

    一键设置文本的段落样式(包括换行模式、文​​本对齐方式等)。

    来自docs

    NSParagraphStyleAttributeName

    该属性的值是一个NSParagraphStyle 对象。使用此属性可将多个属性应用于一系列文本。如果不指定此属性,则字符串使用默认段落属性,由NSParagraphStyledefaultParagraphStyle 方法返回。

    所以,您可以尝试以下方法:

    UIFont *font = [UIFont fontWithName:@"Courier" size:kCellFontSize];
    
    /// Make a copy of the default paragraph style
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    /// Set line break mode
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    /// Set text alignment
    paragraphStyle.alignment = NSTextAlignmentRight;
    
    NSDictionary *attributes = @{ NSFontAttributeName: font,
                        NSParagraphStyleAttributeName: paragraphStyle };
    
    [text drawInRect:rect withAttributes:attributes];
    

    【讨论】:

    • 你是怎么找到这个的? +1
    • 虽然我想不出更短的变化 - 这确实有效,但似乎只是为了添加一些理由!
    • 如何使字符串多行?
    【解决方案2】:

    代码是这样的:

    CGRect textRect = CGRectMake(x, y, length-x, maxFontSize);
    UIFont *font = [UIFont fontWithName:@"Courier" size:maxFontSize];
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    
    
       paragraphStyle.alignment = NSTextAlignmentRight;
        NSDictionary *attributes = @{ NSFontAttributeName: font,
                                      NSParagraphStyleAttributeName: paragraphStyle,
                                      NSForegroundColorAttributeName: [UIColor whiteColor]};
    [text drawInRect:textRect withAttributes:attributes];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多