【问题标题】:Programmatically change title of UIButton not working in iOS Xcode-Beta 3以编程方式更改 UIButton 的标题在 iOS Xcode-Beta 3 中不起作用
【发布时间】:2015-05-28 13:32:11
【问题描述】:

嘿,我正在开发一个小应用程序,它根据日期选择器的当前状态更改 UIButton 的文本。它要么会显示“今天是哪一天?”或“今天是哪一天?”。但是对于 xcode 6.3 beta,UIButton SetTitle 方法似乎不存在。相反,我尝试将字符串分配给 titleLabel.txt,但这不会更改按钮文本。

方法如下:

(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?";
}

我已经看到 setTitle 方法可能是一种解决方案,但发现库可能已更改。任何建议将不胜感激!

【问题讨论】:

    标签: ios objective-c uibutton xcode6


    【解决方案1】:

    你应该这样设置你的标题:

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

    【讨论】:

    • 在我的程序中,发送者是 dateSelector。我希望更改 UIButton 以响应接收到 'Value Changed' 事件。
    • 不用担心,改成上面这行代码就可以了。
    【解决方案2】:

    使用下面的代码设置按钮的标题在不同的状态下和普通状态一样

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

    就好像你点击了你的按钮来选择状态它必须是

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

    就好像您再次单击按钮以取消选择状态一样,它必须是

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

    还有许多其他状态,您可以在按钮的每个状态中设置不同的文本

    【讨论】:

      【解决方案3】:

      尝试改变进行日期比较的方式 -

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

      【讨论】:

        【解决方案4】:

        感谢您的所有建议。第一个建议有点离题,因为我想更改的不是发件人的标题。第二个建议是一个好主意,我将在未来使用。我最终自己解决了这个谜题:

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

        【讨论】:

        • 可以将(id) sender改为(UIButton *) sender,避免使用tempBtn变量
        猜你喜欢
        • 1970-01-01
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 2012-09-21
        • 2015-10-15
        相关资源
        最近更新 更多