简体   繁体   中英

Programmatically change title of UIButton not working in iOS Xcode-Beta 3

Hey I am working on a small app that changes the text of the UIButton based upon the current state of the date selector. It either will show "What day was it?" or "What day will it be?". However with xcode 6.3 beta, the UIButton SetTitle method does not seem to exist. Instead I try to assign a string to titleLabel.txt, but this does not change the button text.

Method is as follows:

(IBAction) changeButton:(id)sender {
NSDate *currentDate = [self.datePicker date];
NSDate *now =  [NSDate date];

if(currentDate<now){
    self.whatButton.titleLabel.text = @"What day was it?";
}
else {
    self.whatButton.titleLabel.text = @"What day will it be?";
}

I have seen that the setTitle method would be a possible solution but discovered that the libraries may have been changed. Any suggestions would be greatly appreciated!

您应该像这样设置标题:

[self.whatButton setTitle:@"What day was it?" forState:UIControlStateNormal];

Use the following code to set the title of the button in different states as if for normal

 [self.yourButton setTitle:@"Default Title" forState:UIControlStateNormal];

as if you have clicked your button for selected state it must be

[self.yourButton setTitle:@"Selected Title" forState:UIControlStateSelected];

as if you have clicked your button again for deselected state it must be

[self.yourButton setTitle:@"Selected Title" forState:UIControlStateDisable];

and many other states you can set different Text in every state of the button

Try changing the way you make the date comparison -

-(IBAction)changeButton:(id)sender {

NSDate *currentDate = [self.datePicker date];
NSDate *now =  [NSDate date];

NSString *titleString = ([currentDate timeIntervalSinceReferenceDate] < [now timeIntervalSinceReferenceDate]) ? @"What day was it?" : @"What day will it be?";
[self.whatButton setTitle:titleString forState:UIControlStateNormal];
}

thank you for all your suggestions. The first suggestion was a little off base since it was not the sender's title that I wanted to change. The second suggestion is a good idea that I will use in the future. I ended up solving the riddle myself with this:

- (IBAction) changeButton:(id)sender {
    NSDate *currentDate = [self.datePicker date];
    NSDate *now =  [NSDate date];
    UIButton *tempBtn = (UIButton *)self.whatButton;
    UIControlState state = tempBtn.state;
    if([currentDate compare:now] == NSOrderedAscending){
        [tempBtn setTitle:@"What day was it?" forState:state];
    }
    else {
        [tempBtn setTitle:@"What day will it be?" forState:state];
    }

}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM