思路: 懒加载 一个View ,在View 上创建N个按钮,点击 按钮 切换 选中 文字
遇到问题: view 可以消失,但是 上面的按钮不会变
原因:可能是 背景的 frame 变了 但是 控件的没有变
解决 办法 : View.clipsToBounds = YES; 超出边缘裁剪
功能代码 :
第一步: 懒加载 一个 View 创建 N 个按钮
pragma mark - 懒加载
-
(UIView *)chooseView{
if (!_chooseView) {
_chooseView = [[UIView alloc] initWithFrame:CGRectMake(JKScreenWidth - 107, 64 + 32, 100, 0)];
_chooseView.clipsToBounds = YES;
[self.view addSubview:_chooseView];
_chooseView.backgroundColor = JKRandomColor;CGFloat y = 0; for (int i = 0 ; i < 4; i ++) { y = i == 0 ? y : y + 120 /4 ; UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, y, 100, 120/4)]; button.tag = 100 + i; [button setTitle:self.titles[i] forState:UIControlStateNormal]; button.titleLabel.textColor = [UIColor colorWithHexString:@"#333333"]; button.titleLabel.font = [UIFont jk_systemFontOfPxSize:24]; [button addTarget:self action:@selector(chooseButtonClick:) forControlEvents:UIControlEventTouchUpInside]; [_chooseView addSubview:button]; }
}
return _chooseView;
}
第二步: 创建需要的文字数组(懒加载)
-
(NSMutableArray *)titles{
if (!_titles) {
_titles = [[NSMutableArray alloc] initWithArray:@[@"所有",@"管理员A",@"管理员B",@"其他"]];
}
return _titles;
}
第三步 : 弹出 View 动画
//筛选按钮点击
-
(void)screenOutButtonClick:(UIButton *)sender{
if (sender.isSelected) {
sender.selected = NO; [UIView animateWithDuration:0.25 animations:^{ self.chooseView.height = 0; }];
}else{
sender.selected = YES; [UIView animateWithDuration:0.25 animations:^{ self.chooseView.height = 120; }];
}
}
第四步: 选择文字后 收起
pragma mark - 类型按钮点击
-
(void)chooseButtonClick:(UIButton *)sender{
[_screenOutButton setTitle:self.titles[sender.tag - 100] forState:UIControlStateNormal];
[UIView animateWithDuration:0.25 animations:^{
self.chooseView.height = 0;
} completion:^(BOOL finished) {
_screenOutButton.selected = NO;
}];
}