ios UIButton設定高亮狀態下的背景色

2022-07-21 12:06:10 字數 1794 閱讀 2683

一,通過按鈕的事件來設定背景色12

3456

78910

1112

1314

1516

1718

1920

2122

- (void)viewdidload

//  button1普通狀態下的背景色

- (void)button1backgroundnormal:(uibutton *)sender

//  button1高亮狀態下的背景色

- (void)button1backgroundhighlighted:(uibutton *)sender

二,通過把顏色轉換為uiimage來作為按鈕不同狀態下的背景12

3456

78910

1112

1314

1516

1718

1920

2122

2324

- (void)viewdidload

//  顏色轉換為背景

- (uiimage *)imagewithcolor:(uicolor *)color

三1.首先,新增乙個按鈕在介面上,我們先設定好普通和高亮狀態時的文字,還有圓角

uibutton *button  = [[uibutton alloc] initwithframe:cgrectmake(100, 100, 100, 40)];

[button settitle:@"normal" forstate:uicontrolstatenormal];

[button settitle:@"highlighted" forstate:uicontrolstatehighlighted];

[button setbackgroundcolor:[uicolor redcolor]];

button.layer.cornerradius = 10.0f;

button.layer.maskstobounds = yes;

[self.view addsubview:button];

// 新增觀察者方法

[self addobserver:button];

2.新增觀察者

/**

* 新增觀察者

* * @param button 需要設定的按鈕

*/- (void)addobserver:(uibutton *)button

3.接下來就是實現觀察者方法

- (void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context 

[button setbackgroundcolor:[uicolor redcolor]];

}}

這樣我們就能在不使用的前提下,實現設定高亮和普通狀態下的背景顏色

看下具體的效果

ios UIButton設定高亮狀態下的背景色

一,通過按鈕的事件來設定背景色 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 void viewdidload button1普通狀態下的背景色 void button1backgroundnormal uibutton sende...

iOS UIButton各類屬性設定大全

設定自定義的按鈕 uibutton button1 uibutton buttonwithtype uibuttontypecustom 設定乙個圓角的按鈕 uibutton button1 uibutton buttonwithtype uibuttontyperoundedrect button...

listView 動態設定高亮

有時候,我們需要動態讓 listview 中的item高亮。比如如下場景。左邊是乙個listview 這個listview 的item是檔案列表 右邊是乙個imageview顯示。如下圖所示 實現方法 listview 的 adapter 繼承自 baseadapter 如下 public clas...