標籤:
第一種方法:依據傳入函數的參數對象的tag屬性區分
比方 多個button運行同一個方法,可是不同的方法運行時。裡面的邏輯又不一樣 那就得加以區分 這時能夠用tag來差別
//再建立一個Button UIButton * button2 = [UIButton buttonWithType:UIButtonTypeSystem]; button2.frame = CGRectMake(20, 60, 280, 30); button2.tag = 2; button2.backgroundColor = [UIColor redColor]; [button2 setTitle:@"點我2" forState:UIControlStateNormal]; //此action中得click:是代表有參數的click方法 [button2 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button2]; //自己定義按鈕 UIButtonTypeCustom UIButton * button3 = [UIButton buttonWithType:UIButtonTypeCustom]; button3.frame = CGRectMake(20, 100, 31, 30); [button3 setTitle:@"點我3" forState:UIControlStateNormal]; button3.tag = 3; //設定button的初始狀態 已經選擇的狀態 button3.selected = NO; //設定自己定義按鈕兩種狀態下得不同圖片 //未選中狀態顯示的是第一個圖片 選中狀態後是後邊的一個圖片 [button3 setImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateNormal]; [button3 setImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateSelected]; [button3 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button3]; }//假設有多個按鈕要觸發同一個操作,可是又想實現不同按鈕方法將運行不同操作時,就要推斷一下是哪個按鈕按下了- (void)click:(UIButton *)button{ if (button.tag == 2) { NSLog(@"button2 點我了"); }else if (button.tag == 3){ NSLog(@"button3 點我了"); }}
2、能夠通過設定全域變數來實現
#import "WJJRootViewController.h"@interface WJJRootViewController (){ <span style="color:#FF0000;">//為全域變數 在此類的不論什麼地方都能夠得到此對象 UIButton * _button3;</span>}@end@implementation WJJRootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self;}3、由於在一個介面中。我們要得到的都是此介面中得控制項,所以能夠通過以下的方法得到
UIButton * btn = (UIButton *)[self.view viewWithTag:3];
Snail—UI學習之得到某組件的方法