Xcode學(xué)習(xí)筆記之動(dòng)態(tài)添加View
Xcode學(xué)習(xí)筆記之動(dòng)態(tài)添加View是本文要介紹的內(nèi)容,前面說的都是用的Interface Builder來編輯.xib文件來給窗口添加各種控件以及給控件綁定數(shù)據(jù)(IBOutlet)、關(guān)聯(lián)事件響應(yīng)函數(shù)(IBAction)。這章學(xué)習(xí)的是動(dòng)態(tài)的添加view,不使用Interface Builder。這里用label和button示例:
找到新建工程XXXViewController.m的-(void)loadView方法,去掉注釋并添加如下代碼
- - (void)loadView {
- //創(chuàng)建一個(gè)UIView 對(duì)象
- UIView *view =
- [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
- view.backgroundColor = [UIColor lightGrayColor];
- //創(chuàng)建一個(gè)label view
- CGRect frame = CGRectMake(10, 15, 300, 20);
- UILabel *label = [[UILabel alloc] initWithFrame:frame];
- label.textAlignment = UITextAlignmentCenter;
- label.backgroundColor = [UIColor clearColor];
- label.font = [UIFont fontWithName:@”Verdana” size:20];
- label.text = @”label test”;
- label.tag = 1000;
- //創(chuàng)建一個(gè)按鈕view
- frame = CGRectMake(10, 30, 300, 50);
- UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- button.frame = frame;
- [button setTitle:@”button test” forState:UIControlStateNormal];
- button.backgroundColor = [UIColor clearColor];
- button.tag = 2000;
/*下面這個(gè)調(diào)用用C++的格式來看就是
- button->addTarget(this->action, @selector(buttonClicked:), UIControlEventTouchUpInside);
中間的action:以及forControlEvent:實(shí)際上都是函數(shù)簽名的一部分。@selector(buttonClicked:) 相當(dāng)于函數(shù)指針(一個(gè)冒號(hào)表明函數(shù)有一個(gè)參數(shù)),這里指向的是buttonClicked函數(shù)
也就是下面定義的按鈕響應(yīng)函數(shù)*/
- [button addTarget:self action:@selector(buttonClicked:) forControlEvent:UIControlEventTouchUpInside];
- [view addSubview:label];
- [view addSubview:button];
- self.view = view;
- [label release];
- }
在這個(gè)文件中添加按鈕響應(yīng)函數(shù)
- -(IBAtion) buttonClicked:(id)sender {
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Action invoked”
- message:@”button clicked”
- delegate:self
- cancelButtonTitle:”@ok”
- otherButtonTitles:nil];
- [alert show];
- [alert release];
- }
label的矩形區(qū)域是CGRectMake(10, 15, 300, 20); 既左上角坐標(biāo)是10,15寬度高度分別是300, 20.
button的矩形區(qū)域的左上角坐標(biāo)是10, 30 ,它們有重疊的地方。
這里遮擋是后加到view里面去的遮擋先加進(jìn)去的。所以button遮擋了label。可以通過
- [view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
來修改遮擋。我的理解是view按照控件加進(jìn)去的順給了個(gè)index,這個(gè)index從0開始遞增。顯示的時(shí)候index數(shù)值較大控件遮擋數(shù)值較小的。 上面這個(gè)函數(shù)交換了***加進(jìn)去的兩個(gè)控件(實(shí)際上只有這兩個(gè))的index。
小結(jié):Xcode學(xué)習(xí)筆記之動(dòng)態(tài)添加View的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!