向视图中添加一个控件:
UIScrollView *weatherBack = [[UIScrollView alloc] initWithFrame:CGRectMake(100, 100, 100, 139)]; //背景色 [weatherBack setBackgroundColor:[UIColor colorWithRed: 255 green:0 blue:0 alpha:0.5]]; //滚动范围 [weatherBack setContentSize:CGSizeMake(421, 139)]; //放入view [[self view]addSubview:weatherBack]; //addsubview会自动retrain,所以这里要四方 [weatherBack release]; |
向控件中添加控件:
UILabel* weekL = [[UILabel alloc] initWithFrame: CGRectMake(5, 3, 50, 30)]; [weekL setText:@”星期三”]; [weekL setFont:[UIFont fontWithName: @"Helvetica-Bold" size:16]]; [weekL setBackgroundColor:[UIColor colorWithRed: 0 green:0 blue:0 alpha:0]]; [weekL setTextColor:[UIColor colorWithRed: 255 green:0 blue:0 alpha:0.9]]; //将label添加到父节点中 [text addSubview:weekL]; [weekL release]; |
响应事件:
//新建一个按钮 UIButton* testB = [[UIButton alloc] initWithFrame: CGRectMake(75, 85, 80, 20)]; [testB setTitle:@"test" forState:UIControlStateNormal]; //将[self testButton]方法 绑定到UIControlEventTouchUpInside [testB addTarget:self action:@selector(testButton:) forControlEvents:UIControlEventTouchUpInside]; [text addSubview:testB]; [testB release]; |
testButton的定义:
//事件处理方法 -(IBAction)testButton:(id)sender{ UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"hello" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil]; [alert show]; [alert release]; } |
以上操作,都可以在xcode自带的“所见即所得”工具“IB”中完成,在书本和网上找到的入门教程也都是使用IB,但大部分时候,我们仍然需要使用代码来做这些工作
————