【问题标题】:UIButton setTitleColor and setImage not workingUIButton setTitleColor 和 setImage 不起作用
【发布时间】:2012-05-07 09:50:24
【问题描述】:

我正在为我的 iPhone 项目使用 StoryBoard 功能。在情节提要中,我有一个使用原型单元格的带有表格视图的视图控制器。在原型单元格内,我有一个 UIButton(圆角矩形)连接到一个子类 UIButton 类。 tableview 从数组中获取数据,数据在 cellForRowAtIndexPath 中打印出来。

在 cellForRowAtIndexPath 中,我有条件地修改了单元格的外观。这是我开始遇到问题的时候。我能够成功更改按钮的文本。但是,如果我尝试更改按钮的图像,请使用:

[cell.myButton setImage:[UIImage imageNamed:@"mynewimage.png"] forState:UIControlStateNormal];

图像改变了,但文字消失了。

如果我尝试更改按钮的文本颜色,请使用:

[cell.myButton setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.77] forState:UIControlStateNormal]

什么都没有发生。颜色保持不变(除非我也尝试更改图像,在这种情况下它会完全消失)。

我感觉到我在这里做了一些根本性的错误——你有什么建议吗?

【问题讨论】:

    标签: iphone uitableview uibutton


    【解决方案1】:

    使用

    - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;   
    

    用左边的文字改变图像

    使用

    btn.titleLabel.textColor = yourcolor;
    

    改变文字颜色

    【讨论】:

    • 太好了,现在图像设置正确(文字没有消失)。但是,文本颜色没有任何反应...
    【解决方案2】:

    如下定义myButton并检查。这可能是你的代码错误。代码是:

    myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    

    这是新编辑的部分:

    [myButton setBackgroundImage:yourimage forState:UIControlStateNormal];
        [myButton setTitleColor:yourcolor forState:UIControlStateNormal];
    

    【讨论】:

    • 按钮不是以编程方式添加的——它是在情节提要中添加的。
    【解决方案3】:

    这是为自定义按钮设置不同属性的方法...您还可以在此处找到 setBackgroudimage 和 setTitleColor 属性...

        UIButtin  *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
       [myButton setFrame:CGRectMake(165, 205, 65, 40)];
       [myButton setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.77]  forState:UIControlStateNormal];
       [myButton setTitle:@"Hi....." forState:UIControlStateNormal];
       [myButton addTarget:self action:@selector(btnClicked:)     forControlEvents:UIControlEventTouchUpInside];
       [myButton setBackgroundImage:[UIImage imageNamed:@"mynewimage.png"] forState:UIControlStateNormal];
       [cell  addSubview:myButton];
    

    谢谢你..

    【讨论】:

      【解决方案4】:

      我猜你想要的是改变你的按钮背景:

      [cell.myButton setBackgroundImage:[UIImage imageNamed:@"mynewimage.png"] forState:UIControlStateNormal];
      

      【讨论】:

        【解决方案5】:

        您的文字消失了,因为您已将按钮正面的图像设置为按钮主图像。

        [cell.myButton setImage:[UIImage imageNamed:@"mynewimage.png"] forState:UIControlStateNormal];
        

        您需要设置按钮背景图像,以便在您的 UIButton 上下文的后侧绘制图像时您的文本可见。

        所以只需将上面的代码行替换为:

        [cell.myButton setBackgroundImage:[UIImage imageNamed:@"mynewimage.png"] forState:UIControlStateNormal];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-31
          • 2018-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多