【问题标题】:NSMutableString append stringNSMutableString 附加字符串
【发布时间】:2013-10-28 13:24:16
【问题描述】:

初学者问题:

有三个按钮,分别代表字母 a、e 和 i。 按下按钮时,相应的字母应显示在标签中。 因此,当每个按钮按下一次时,标签会显示“aei”。 下面附上我的代码。现在按三下按钮时,标签 仅显示最后按下的按钮字母。 我究竟做错了什么? 感谢您的帮助!


#import "SecondViewController.h"


NSMutableString *stringLabel;


@interface SecondViewController ()
@end

@implementation SecondViewController




-(IBAction)type_a:(id)sender;{
[stringLabel appendString: @"a"];
NSLog(@"stringLabel is set to: %@", stringLabel);
label.text = stringLabel;


}

-(IBAction)type_e:(id)sender;{
[stringLabel appendString: @"e"];
NSLog(@"stringLabel is set to: %@", stringLabel);
label.text = stringLabel;


}

-(IBAction)type_i:(id)sender;{
[stringLabel appendString: @"i"];
NSLog(@"stringLabel is set to: %@", stringLabel);
label.text = stringLabel;


}

【问题讨论】:

    标签: nsmutablestring


    【解决方案1】:

    我不知道你在哪里初始化你的 NSMutableString 但也许你错过了这个:

    stringLabel = [[NSMutableString alloc] init];
    

    将该代码放入 viewDidLoad 中,它应该可以工作,因为您的代码是正确的。

    另外,你在哪里设置标签和视图控制器之间的连接?我看不到

    @property (weak, nonatomic) IBOutlet UILabel *label;
    

    也检查一下

    【讨论】:

    • 谢谢,我的标签连接出现错误。再次建立连接,现在它可以工作了!再次感谢!
    【解决方案2】:

    每次在您的帖子中,您都在使用标签为标签赋值

        label.text = stringValue
    

    通过删除旧值分配新值

    你必须将旧字符串与新字符串值连接起来。

    将 Label 的先前值存储在 NSMutableString 中,例如

        NSMutableString *previosValue = label.text;
    

    现在将 buttonValue 连接到 previousValue 并添加到标签

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多