以编程方式更改工具栏上的UILabel(UIBarButtonItem)的文本

cra*_*ash 6 iphone

我是初学的iPhone开发者.我的代码如下:

UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
UILabel *lblTotCaratteri = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 25, 15)];
lblTotCaratteri.textAlignment = UITextAlignmentCenter;
lblTotCaratteri.font = [UIFont italicSystemFontOfSize:13.0];
lblTotCaratteri.textColor = [UIColor greenColor];
lblTotCaratteri.backgroundColor = [UIColor clearColor];
lblTotCaratteri.adjustsFontSizeToFitWidth = YES;
lblTotCaratteri.text = @"0";

UIBarButtonItem *lblCaratteri = [[UIBarButtonItem alloc] initWithCustomView: lblTotCaratteri];

inserimentoToolbar.items = [NSArray arrayWithObjects:fixedSpace, lblCaratteri, fixedSpace, nil];
Run Code Online (Sandbox Code Playgroud)

所以在我看来,我有一个UITextView,这个工具栏以编程方式创建.我想在每次向UITextView添加字符时更改标签文本.每次UITextView文本更改时,我都会显示每个按键的警报.我无法弄清楚如何更改标签文字.我希望我已经解释了我的情景.对不起我的英语不好.问候,卢卡.

Nei*_*eil 6

一种方法是,假设在您的界面中声明了inserimentoToolbar:

[(UILabel *)[[toolbar.items objectAtIndex:1] view] setText:@"sometext"];
Run Code Online (Sandbox Code Playgroud)

这实际上只有在您的工具栏不会更改时(就对象而言)才有效.

要么

更理想的解决方案是将lblTotCaratteri放在您的界面中(在头文件中).喜欢:

@interface UntitledViewController : UIViewController {
    UILabel *lblTotCaratteri;
}
Run Code Online (Sandbox Code Playgroud)

那么你所包含的代码就是这样的

UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
lblTotCaratteri = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 25, 15)];
lblTotCaratteri.textAlignment = UITextAlignmentCenter;
// etc etc etc
Run Code Online (Sandbox Code Playgroud)

然后在任何时候,只需使用

lblTotCaratteri.text = @"sometext";
Run Code Online (Sandbox Code Playgroud)


小智 5

哟,这对我有用,当我点击相同的UIBarButtonItem时,我更改了UIBarButtonItem标题.意味着我需要的是触发器.如果第一次单击它会显示"MyText1",然后再次单击,标题将更改为"MyText2".用户单击按钮时文本切换.

-(IBAction)myBarButtonItem:(id)item{

 if(flag){
   flag=FALSE;
   [(UIBarButtonItem *)item setTitle:@"MyText1"];
}
else{
  flag=TRUE;
  [(UIBarButtonItem *)item setTitle:@"MyText2"];
}
Run Code Online (Sandbox Code Playgroud)

注意:我还没有以编程方式创建UIBarButtonItem.我在Interface Builder中创建并将方法"myBarButtonItem"的引用设置为此按钮.因此,当UIBarButtonItem或按下这种类型的按钮时,它调用方法"myBarButtonItem"并发送按钮的引用作为参数,我进一步输入(UIBarButtonItem*)并使用setTitle属性来更改它的文本或说标题.

***声明方法的签名即在你的头文件中: - (IBAction)myBarButtonItem:(id)item;