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

iOS-自定义标签及其控件(一)

2016-07-22 10:45 435 查看
#pragma mark - 自定义标签及其控件
- (void) createTabBar {

//1.加载背景图片
self.tabBar.backgroundImage = [UIImage imageNamed:@"splash_bottom"];

//2. 定义按钮
//1) 将按钮的图片名存放在数组中
NSArray *imageArray = @[ @"trends", @"find", @"message", @"my" ];
//2) 每个button(item)的宽度,注意超过5个的情况,会有一个更多按钮
float buttonWidth = kScreenWidth / imageArray.count;

//3) 使用for循环,创建5个button
for (int i = 0; i < imageArray.count; i++) {

//a) 从数组中获取图片的名称
NSString *imageName = imageArray[i];
//b) 设置普通图片名称
NSString *normalImageName = [NSString stringWithFormat:@"trends_%@_normal", imageName];
//c) 设置点击状态的图片名称
NSString *clickImageName = [NSString stringWithFormat:@"trends_%@_click", imageName];

//d) 定义一个button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//e) 设置tag
button.tag = 1000 + i;
//f) 设置frame
button.frame = CGRectMake(i * buttonWidth, 0, buttonWidth, 49);
//g) 设置图片的效果
[button setImage:[UIImage imageNamed:normalImageName] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:clickImageName] forState:UIControlStateSelected];
//h) 响应时间
[button addTarget:self
action:@selector(buttonTabBarAction:)


forControlEvents:UIControlEventTouchUpInside];

//i) 添加到tabBar

[self.tabBar addSubview:button];

//j) 默认选中第一个按钮
if (i == 0) {
button.selected = YES;
}
}
}

#pragma mark - 标签的选择响应事件
- (void) buttonTabBarAction: (UIButton *) button {

//1) 通过button的tag来进行选择不同的标签
self.selectedIndex = button.tag - 1000;

//2) 图片的效果修改
for (int i = 0; i < 4; i++) {
//a) 获取button
UIButton *buttonWithTag = (UIButton *)[self.tabBar viewWithTag:1000 + i];
//b) 判断:如果选择的button的tag和获取的tag一致,那么就修改其button的图片
if (buttonWithTag.tag == button.tag) {
buttonWithTag.selected = YES;
} else {
buttonWithTag.selected = NO;
}
}
}

#pragma mark - 使用viewDidAppear来消除“重影”
- (void) viewDidAppear:(BOOL)animated {
//移除系统自带的标签栏
[self removeUITabBarButton];
}

#pragma mark - 移除系统自带的标签栏
- (void) removeUITabBarButton {

//-----------------移除系统自带的tabBarButton-----------------
//1) 循环获取标签栏的所有的子视图
for (UIView *view in self.tab    Bar.subviews) {
//2) 比较,如果视图是系统自带的,那么就移除
//  方法说明:NSClassFromString -----> 通过字符串获取类名
if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
[view removeFromSuperview];
}

//3) 有些视图中可能会出现比较诡异的横线,这里提供一种移除方案,特别说明:本案例中无此问题
if ([view isKindOfClass:[UIImageView class]] && view.bounds.size.height <= 1) {
[view removeFromSuperview];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  控件 TabBar-iOS