【问题标题】:How to Change textLabel property in UIButton programmatically in iOS?如何在 iOS 中以编程方式更改 UIButton 中的 textLabel 属性?
【发布时间】:2012-06-21 09:44:45
【问题描述】:

我有一个UIButton,它应该有两种状态——“播放”和“暂停”;即 - 用户第一次看到它时会说“播放”,然后每当用户点击它时,它应该在“播放”和“暂停”之间切换。

我设法自己创建了控制器 - 内容已正确播放和暂停 - 但我似乎无法更改 UIButton 文本标签文本。

我用:

myButton.titleLabel.text = @"Play";

myButton.titleLabel.text = @"Pause";

它不工作。文本没有变化。我也尝试了 [myButton.titleLabel setText:@"Pause"],但效果不佳。

如何设置?

【问题讨论】:

    标签: ios uibutton label title


    【解决方案1】:

    应该是:

    [myButton setTitle:@"Play" forState:UIControlStateNormal];
    

    您还需要传递state。您可以查看其他statehere

    然后你可以这样做:

    [myButton setTitle:@"Play" forState:UIControlStateNormal];
    [myButton setTitle:@"Stop" forState:UIControlStateSelected];
    

    【讨论】:

      【解决方案2】:

      SWIFT 4

      myButton.setTitle("Pause", for: .normal)
      

      【讨论】:

        【解决方案3】:

        我发现这有点过时,因为添加了属性字符串。显然,故事板中分配的按钮标题是属性字符串。属性标题优先于 NSString 标题,所以如果你想使用一个简单的字符串作为标题,你必须先删除属性标题。我做了如下,虽然可能有更好的方法。当然,您可以将新标题也设为属性字符串。

        [myButton setAttributedTitle: nil     forState: 0xffff];
        [myButton           setTitle: @"Play" forState: UIControlStateNormal];
        

        【讨论】:

          【解决方案4】:

          如果你想在页面加载时加载它,并支持本地化语言:

          -(void)viewDidAppear:(BOOL)animated
          {
              [super viewDidAppear:animated];
              if (self.flagToChangeLabel){
                  NSString* newBtnTitle = NSLocalizedString(@"LOCALIZED_KEY", nil);
                  [self.laterButton setTitle:newBtnTitle forState:UIControlStateNormal];
                  [self.laterButton setTitle:newBtnTitle forState:UIControlStateSelected];
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2014-11-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-15
            • 2014-08-22
            • 2012-09-21
            • 1970-01-01
            • 2021-05-06
            相关资源
            最近更新 更多