【问题标题】:Why doesn't UIButton title display?为什么 UIButton 标题不显示?
【发布时间】:2009-06-26 04:02:21
【问题描述】:

在 UIViewController 的 viewDidLoad 方法中,我这样做:

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];                       // EDIT: should be 'b'
NSLog(@"button title: %@", [b titleLabel].text);

按钮显示,但标题不显示。 NSLog 行将“Testing”打印到控制台。关于我做错了什么有什么建议吗?

【问题讨论】:

  • 两个想法: * 如果你让按钮变大会发生什么? * 您是否在 viewDidLoad 中做任何其他可能影响按钮的操作?
  • 请参阅下面 dieerikh 的解决方案,因为它描述了上面使用的双重初始化程序中的错误以及对它的修复,即在便利初始化程序 [... 按钮之后单独分配框架type ...] 完成。 OP 自己的解决方案的其余部分是正确的,并且保持不变。

标签: iphone cocoa-touch uiview uiviewcontroller uibutton


【解决方案1】:

我不能告诉你为什么它不起作用,但我确实有一个解决方案:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;        
b. frame = CGRectMake(0, 0, 100, 100);

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self addSubview:b];   

将框架与按钮的分配和初始化分开。

【讨论】:

  • 我同意。我敢打赌,像您正在做的那样将两个初始化程序链接在一起会导致一些问题。使用 buttonWithType 然后设置框架。
  • 是的,buttonWithType 是一个静态工厂方法,它返回一个完全初始化的按钮。您不能在已经初始化的按钮上调用initWithFrame(结果充其量是未定义的)。 init 方法只能在 alloc 之后调用。
【解决方案2】:

问题出在

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

buttonWithType 返回一个自动释放的初始化对象。您不能再次向它发送 initWithFrame,因为对象只能初始化一次。

单独设置它的框架:

b.frame = CGRectMake(0, 0, 100, 100);

【讨论】:

    【解决方案3】:

    改为这样做:

    UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    b.frame = CGRectMake(0, 0, 100, 100);
    [b setTitle:@"Testing" forState:UIControlStateNormal];
    [b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
    [self.view addSubview:b];  
    

    【讨论】:

      【解决方案4】:

      问题是你必须选择[[UIButton alloc] initWithFrame:][UIButton buttonWithType:],你不应该同时使用两者。

      【讨论】:

        【解决方案5】:

        您可以执行以下操作:

        UIButton *b=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        

        b=[UIButton buttonWithType:UIButtonTypeRoundedRect];

        [b setTitle:@"Button Title Here" forState:UIControlStateNormal];
        [b setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
        [self.view addSubview:b];
        

        【讨论】:

          【解决方案6】:

          我遇到了同样的问题,结果是我设置的是图像而不是背景图像。当我这样做时一切正常:

          [button setBackgroundImage:image forState:UIControlStateNormal];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-07-25
            • 2017-11-24
            • 1970-01-01
            • 2012-09-12
            • 1970-01-01
            • 2020-06-29
            相关资源
            最近更新 更多