子类化UIButton的背景颜色?

时间:2011-06-27 09:55:44

标签: iphone xcode uibutton

我有一个UIButton子类,我将其初始化为:

MyButton *button = [MyButton buttonWithType:UIButtonTypeCustom];

我想设置此按钮的背景颜色。

如果我在创建按钮后在视图控制器中执行以下操作:

MyButton.backgroundColor = [UIColor ...];

工作正常。但是,如果我尝试在UIButton子类中执行以下操作,请initWithFrameDrawRect:

self.backgroundColor = [UIColor ...];

它什么都不做。按钮保持透明。

问题是,我的逻辑是这样的,我真的需要在UIButton子类中设置颜色,而不是在调用代码中。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

UIButton并不意味着是子类。它是一个类集群,你几乎肯定会弄错(现在或将来可能会破坏)。基本方法buttonWithType:也永远不会返回您的类的实例,因此您需要竭尽全力使所有代码都能正常工作。

很多更好的方法是制作一个使用UIButton.buttonWithType:的工厂方法,并按照您需要的方式配置按钮。

答案 1 :(得分:0)

你能在你的子类中实现“Buttonwithtype”方法并在那里编写代码self.backgroundColor = [UIColor WhateverColor];

它应该工作。让我知道。

相关问题