您的位置:首页 > 移动开发 > IOS开发

IOS开发---小小规律总结之控件的获取和使用

2015-06-26 18:27 726 查看
学习IOS开发发现一点小小的规律。

纯属个人理解

1. 如何使用一个控件。

1)初始化控件:使用alloc, initWithXXX方法。

2)设置控件的frame:就是确定控件显示的位置,宽度和高度。通常需要计算和定义常量,尽量不要写死。

3)设置控件的属性:属性包括标题,背景,背景包括图片和颜色等。

4)设置控件的事件响应:使用addTarget的方式为控件添加事件响应函数。

5)添加控件到父容器中:通常使用[xxxx addSubview: xxxx]的方式实现。

举例说明:添加按钮到标签栏

//customize tab bar
- (void)initTabBarView{
//initial tab bar view
_tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - tabViewHeight, kScreenWidth, tabViewHeight)];
_tabBarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mask_navbar"]];
[self.view addSubview:_tabBarView];

//add a array and get the images
NSArray *imageArray = @[@"home_tab_icon_1",@"home_tab_icon_2",@"home_tab_icon_3",@"home_tab_icon_4",@"home_tab_icon_5"];

//create buttons
for (int i = 0; i < imageArray.count; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

[btn setBackgroundImage:[UIImage imageNamed:imageArray[i]] forState:UIControlStateNormal];

btn.frame = CGRectMake(btnWidth * i, (tabViewHeight - btnHeight)/2, btnWidth, btnHeight);

//set tag for button, and make sure tag is great than 100 since the number less than 100 has been reserved by system
btn.tag = 100 + i;
//add click event for button
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

[self.tabBarView addSubview:btn];
}
//initial selected imageview
_selectView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
_selectView.image = [UIImage imageNamed:@"home_bottom_tab_arrow"];
[_tabBarView addSubview:_selectView];
}
2. 获取一个view controller,然后使用它的方法

通常使用强制类型转换的方法,把想要的VC得到。如下:利用了contentview中的tabBarController属性得到标签控制器,然后使用标签控制器中的方法。

RootViewController *rootVC = (RootViewController *)self.tabBarController;

[rootVC showTabBar:NO];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios开发