Ios UIButton固定了在目标C中单击时的背景色
我一直在尝试将按钮的背景色固定在.xib上。就像,默认背景是白色的,但是当点击按钮时,它将是蓝色或黑色的,并且在点击另一个按钮之前,它将保持这种状态。 我使用Ios UIButton固定了在目标C中单击时的背景色,ios,objective-c,xcode,uibutton,xib,Ios,Objective C,Xcode,Uibutton,Xib,我一直在尝试将按钮的背景色固定在.xib上。就像,默认背景是白色的,但是当点击按钮时,它将是蓝色或黑色的,并且在点击另一个按钮之前,它将保持这种状态。 我使用uicontrol状态、背景色和图像进行了大多数组合,但似乎没有任何效果。背景颜色更改一秒,一秒后变为默认颜色 这是我尝试过的组合之一 [self.theButton addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpIns
uicontrol状态
、背景色和图像进行了大多数组合,但似乎没有任何效果。背景颜色更改一秒,一秒后变为默认颜色
这是我尝试过的组合之一
[self.theButton addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside];
-(void) slideAction:(UIButton *)myButton
{
[self.theButton setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal];
}
函数工作,但不更新颜色。我不知道这个问题是否与.xib有关。
我很感激你能帮我解决这个问题。
谢谢。在该按钮上单击“输入以下代码”
-(void) slideAction:(UIButton *)myButton
{
[self.theButton setBackgroundColor:[UIColor blueColor]];
}
然后再点击一个按钮
-(void) AnotherButtonAction:(UIButton *)myButton
{
[self.theButton setBackgroundColor:[UIColor whiteColor]];
}
请遵循以下方法:
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state;
这是因为
backgroundColor
是UIView
的一个属性,正如您所知UIButton
是UIView
的一个子类
这一点很重要,因为这样就更容易理解此属性没有状态的原因:视图没有状态。出于某种原因,苹果决定对按钮的属性行为进行扩展
在iOS中创建的根据状态更改UI按钮背景颜色的方法是:setBackgroundImage:forState:
。我知道,这意味着你需要每个州的形象。浪费空间和记忆
为了解决这个问题,我创建了一个类别,用ui按钮处理backgroundColor
状态:
按钮背景颜色
您可以将该类别安装为
或者用老办法:将文件夹拖到项目中。就这些
易于与Objective-C一起使用
@property (nonatomic, strong) UIButton *myButton;
...
[self.myButton bbc_backgroundColorNormal:[UIColor redColor]
backgroundColorSelected:[UIColor blueColor]];
使用Swift更加方便:
import ButtonBackgroundColor
...
let myButton:UIButton = UIButton(type:.Custom)
myButton.bbc_backgroundColorNormal(UIColor.redColor(), backgroundColorSelected: UIColor.blueColor())
我建议您通过以下方式导入pod:
platform :ios, '8.0'
use_frameworks!
pod 'ButtonBackgroundColor', '~> 1.0'
使用use_框架!在您的Podfile中,使用Swift和objective-C可以更轻松地使用您的pod
重要
[myButton setBackgroundImage:[UIColor greenColor]]用于状态:UIControlStateHighlighted]//根据你的要求改变状态和颜色检查这篇文章和这个pod我希望我的回答能帮助你。
platform :ios, '8.0'
use_frameworks!
pod 'ButtonBackgroundColor', '~> 1.0'