Xcode學習筆記之動態(tài)添加View
Xcode學習筆記之動態(tài)添加View是本文要介紹的內(nèi)容,前面說的都是用的Interface Builder來編輯.xib文件來給窗口添加各種控件以及給控件綁定數(shù)據(jù)(IBOutlet)、關聯(lián)事件響應函數(shù)(IBAction)。這章學習的是動態(tài)的添加view,不使用Interface Builder。這里用label和button示例:
找到新建工程XXXViewController.m的-(void)loadView方法,去掉注釋并添加如下代碼
- - (void)loadView {
- //創(chuàng)建一個UIView 對象
- UIView *view =
- [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
- view.backgroundColor = [UIColor lightGrayColor];
- //創(chuàng)建一個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)建一個按鈕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;
/*下面這個調(diào)用用C++的格式來看就是
- button->addTarget(this->action, @selector(buttonClicked:), UIControlEventTouchUpInside);
中間的action:以及forControlEvent:實際上都是函數(shù)簽名的一部分。@selector(buttonClicked:) 相當于函數(shù)指針(一個冒號表明函數(shù)有一個參數(shù)),這里指向的是buttonClicked函數(shù)
也就是下面定義的按鈕響應函數(shù)*/
- [button addTarget:self action:@selector(buttonClicked:) forControlEvent:UIControlEventTouchUpInside];
- [view addSubview:label];
- [view addSubview:button];
- self.view = view;
- [label release];
- }
在這個文件中添加按鈕響應函數(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); 既左上角坐標是10,15寬度高度分別是300, 20.
button的矩形區(qū)域的左上角坐標是10, 30 ,它們有重疊的地方。
這里遮擋是后加到view里面去的遮擋先加進去的。所以button遮擋了label。可以通過
- [view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
來修改遮擋。我的理解是view按照控件加進去的順給了個index,這個index從0開始遞增。顯示的時候index數(shù)值較大控件遮擋數(shù)值較小的。 上面這個函數(shù)交換了***加進去的兩個控件(實際上只有這兩個)的index。
小結:Xcode學習筆記之動態(tài)添加View的內(nèi)容介紹完了,希望本文對你有所幫助!