【问题标题】:How can I convert the characters in an NSString object to UILabel objects?如何将 NSString 对象中的字符转换为 UILabel 对象?
【发布时间】:2010-10-29 01:05:16
【问题描述】:

我试图弄清楚如何获取 NSString 对象中的单个字符并从中创建 UILabel,并将 UILabel 文本设置为单个字符。

我是 Cocoa 的新手,但到目前为止我有这个......

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];
}

除了我遇到的困难之外,我的方法已经感觉很老套了,但我还是个菜鸟,还在学习。任何有关如何解决此问题的建议都会非常有帮助。

非常感谢您的帮助!

【问题讨论】:

  • 出于好奇,您为什么要这样做?您可能会创建大量 UILabel,但效率不高。
  • 这只是一种快速测试我正在开发的游戏的一些游戏功能的方法。这是暂时的。

标签: objective-c cocoa uikit ios nsstring


【解决方案1】:

您想将-substringWithRange: 与长度为 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];
}

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 2011-10-24
    • 2022-01-20
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2010-12-05
    相关资源
    最近更新 更多