Search code examples
iosnsstringnsattributedstring

Drawing vertical text on iOS


I'd like to draw an NSAttributedString (or NSString) vertically on iOS. By "vertically" I mean:

Vertical text example

Apple's documentation says a standard attribute on an NSAttributedString is NSVerticalGlyphFormAttributeName, but unfortunately, says:

"In iOS, horizontal text is always used and specifying a different value is undefined."

The same document also mentions NSTextLayoutSectionsAttribute, which seems to support NSTextLayoutOrientation, which allows NSTextLayoutOrientationHorizontal or NSTextLayoutOrientationVertical.

None of those 4 terms get any hits on SO at the moment. Just that lonely whistling sound.

However, I don't have any idea how to set this up, whether it works with iOS, or if can be used for vertical string rendering in the style of [myAttributedString drawAtPoint: whereItOughtaGo].

Thanks.


Solution

  • If it just a single lined text as in your example you can use various workarounds. I would personally create a UILabel subclass as follows:

    @implementation VerticalLabel
    
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
      self = [super initWithCoder:aDecoder];
    
      if (self) {
        self.numberOfLines = 0;
      }
    
      return self;
    }
    
    - (void)setText:(NSString *)text {
      NSMutableString *newString = [NSMutableString string];
    
      for (int i = text.length-1; i >= 0; i--) {
        [newString appendFormat:@"%c\n", [text characterAtIndex:i]];
      }
    
      super.text = newString;
    }
    
    @end
    

    Now you just have to replace:

    UILabel *lbl = [[UILabel alloc] init];
    

    with:

    UILabel *lbl = [[VerticalLabel alloc] init];
    

    to get vertical text.