Snail—UI學習之得到某組件的方法

來源:互聯網
上載者:User

標籤:

第一種方法:依據傳入函數的參數對象的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學習之得到某組件的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.