align text using drawInRect:withAttributes:

前端 未结 2 673
轻奢々
轻奢々 2020-12-07 14:18

In the iOS 5 version of my app I had:

[self.text drawInRect: stringRect
             withFont: [UIFont fontWithName: @\"Courier\" size: kCellFontSize]
               


        
相关标签:
2条回答
  • 2020-12-07 14:32

    There is one key to set the paragraph style of the text (including line breaking mode, text alignment, and more).

    From docs:

    NSParagraphStyleAttributeName

    The value of this attribute is an NSParagraphStyle object. Use this attribute to apply multiple attributes to a range of text. If you do not specify this attribute, the string uses the default paragraph attributes, as returned by the defaultParagraphStyle method of NSParagraphStyle.

    So, you can try the following:

    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];
    
    0 讨论(0)
  • 2020-12-07 14:48

    The code is going that way:

    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];
    
    0 讨论(0)
提交回复
热议问题