Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

iphone - Change the text of a UILabel (UIBarButtonItem) on a toolbar programmatically

I'm a beginner iPhone developer. My code is the following:

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

So in my view I have a UITextView and this toolbar created programmatically. I want to change the label text each time I add a character to the UITextView. Each time the UITextView text changes, I can display an alert each key pressed. I can't figure out how to change the label text. I hope I've explained my scenario. Sorry for my English. Greetings, Luca.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way would be, assuming inserimentoToolbar is declared in your interface:

[(UILabel *)[[toolbar.items objectAtIndex:1] view] setText:@"sometext"];

This really only works assuming your toolbar doesn't change (in terms of objects).

OR

The more ideal solution would be to put lblTotCaratteri in your interface (in your header file). Like:

@interface UntitledViewController : UIViewController {
    UILabel *lblTotCaratteri;
}

Then your included code would just like

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

Then at any point, just use

lblTotCaratteri.text = @"sometext";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...