2016-01-06 40 views
0

我一直在試圖讓按鈕的背景色固定在.xib上。就像,默認背景是白色的,但是當按鈕被點擊時,它會變成藍色或黑色,並且它會一直保持到另一個按鈕被點擊。 我做了大部分與UIControlState,背景顏色和圖像的組合,但似乎沒有任何工作。背景顏色每秒改變一次,並在一秒後進入默認狀態。UIButton在點擊時固定背景色目標C

這是組合的一個我試圖

[self.theButton addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventTouchUpInside]; 
-(void) slideAction:(UIButton *)myButton 
{ 
    [self.theButton setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateNormal]; 
} 

功能的作品,但它不更新的顏色。我不知道這個問題是否與.xib有關。 我很欣賞你能幫助我解決這個問題。 謝謝。

該按鈕點擊
+0

[myButton的了setBackgroundImage:[自imageWithColor:的UIColor綠彩] forState:UIControlStateHighlighted]; //根據您的要求更改狀態和顏色 – nikhil84

+0

查看該帖子https://somethingaboutios.wordpress.com/2016/02/09/uibutton-backgroundcolor-for-uicontrolstateselected/並且這個窗口https://github.com/GabrielMassana/ButtonBackgroundColor-iOS –

+0

我希望我的回答能幫助你。 –

回答

0

就把下面的代碼

-(void) slideAction:(UIButton *)myButton 
{ 
    [self.theButton setBackgroundColor:[UIColor blueColor]]; 
} 

,並把這些代碼另一次按點擊

-(void) AnotherButtonAction:(UIButton *)myButton 
    { 
     [self.theButton setBackgroundColor:[UIColor whiteColor]]; 
    } 
0

請按照此方法:

- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state; 
0
Try below code 

    -(void)code:(UIButton *)sender 
    { 
     for (UIView* subView in self.view.subviews) 
     { 
      if ([subView isMemberOfClass:[UIButton class]]) 
      { 
       [subView setBackgroundColor:[UIColor greenColor]]; 
       [sender setBackgroundColor:[UIColor blackColor]]; 
      } 
     } 
    } 

    -(IBAction)firstBtnAction:(id)sender 
    { 
     [self code:sender]; 
    } 

    -(IBAction)secondBtnAction:(id)sender 
    { 
     [self code:sender]; 
    } 

    -(IBAction)thirdBtnAction:(id)sender 
    { 
     [self code:sender]; 
    } 

    -(IBAction)fourthBtnAction:(id)sender 
    { 
     [self code:sender]; 
    } 
0

這是因爲backgroundColorUIView的財產,因爲您知道UIButtonUIView的子類。

這很重要,因爲它更容易理解爲什麼這個屬性沒有國家:視圖沒有狀態。出於某種原因,Apple決定做點擴展按鈕的屬性行爲。

在iOS中創建的用於根據狀態更改UIButtons的backgroundColor的方法是:setBackgroundImage: forState:。我知道,這意味着你需要每個國家的形象。浪費空間和記憶。

爲了解決這個問題,我創建了一個類來處理backgroundColorUIButtons
ButtonBackgroundColor-IOS

您可以安裝類別爲pod

或者做老派的方式:拖入你的項目文件夾/ButtonBackgroundColor-iOS。就這樣。

容易與Objective-C的使用

@property (nonatomic, strong) UIButton *myButton; 

... 

[self.myButton bbc_backgroundColorNormal:[UIColor redColor] 
       backgroundColorSelected:[UIColor blueColor]]; 

更容易與斯威夫特使用:

import ButtonBackgroundColor 

... 

let myButton:UIButton = UIButton(type:.Custom) 

myButton.bbc_backgroundColorNormal(UIColor.redColor(), backgroundColorSelected: UIColor.blueColor()) 

我建議你導入莢:

platform :ios, '8.0' 
use_frameworks! 

pod 'ButtonBackgroundColor', '~> 1.0' 

使用use_frameworks !在你的Podfile中,使用Swift和objective-C更容易使用你的豆莢。

重要

I also wrote a Blog Post with more information.