开发者

How can I convert the characters in an NSString object to UILabel objects?

开发者 https://www.devze.com 2023-01-22 17:18 出处:网络
I\'m trying to figure out how to take the individual characters in an NSString object and create UILabels from them, with the UILabel text set to the individual character.

I'm trying to figure out how to take the individual characters in an NSString object and create UILabels from them, with the UILabel text set to the individual character.

I'm new to Cocoa, but so far I have this...

NSString *myString = @"This is a string object";

for(int i = 0; i < [myString length]; i++)
{
  //Store the character
  UniChar chr = [myString characterAtIndex:i];

  //Stuck here, I need to开发者_运维知识库 convert character back to an NSString object so I can...

  //Create the UILabel
  UILabel *lbl = [[UILabel alloc] initWithFrame....];
  [lbl setText:strCharacter];

  //Add the label to the view
  [[self view] addSubView:lbl];
}

Aside from where I'm stuck, my approach already feels very hackish, but I'm a noob and still learning. Any suggestions for how to approach this would be very helpful.

Thanks so much for all your help!


You want to use -substringWithRange: with a substring of length 1.

NSString *myString = @"This is a string object";

NSView *const parentView = [self superview];
const NSUInteger len = [myString length];
for (NSRange r = NSMakeRange(0, 1); r.location < len; r.location += 1) {
    NSString *charString = [myString substringWithRange:r];

    /* Create a UILabel. */
    UILabel *label = [[UILabel alloc] initWithFrame....];
    [lbl setText:charString];

    /* Transfer ownership to |parentView|. */
    [parentView addSubView:label];
    [label release];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消