/*
模拟输入内容时,控件不被键盘遮挡的效果
PS:实际工作中可利用三方库实现这种效果
思路:
1.点击按钮,改变遮挡层(UIView)y坐标,令其下降
2.点击按钮1,通过flag标识改变遮挡层y坐标,令其上升,按钮1的坐标随着遮挡层的改变而上升,且改变了flag的值
3.点击按钮1,通过flag标识改变遮挡层y坐标,令其下降,按钮1的坐标随着遮挡层的改变而下降,且改变了flag的值 */
附上完整代码:http://yunpan.cn/cHaGEuqp3d7BH (提取码:3296)
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
//UIButton
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 40);
button.backgroundColor = [UIColor blueColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
// 模拟textFiled 输入内容时被遮挡的情况
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = CGRectMake(100, 667-190, 100, 40);
button1.backgroundColor = [UIColor blueColor];
[self.view addSubview:button1];
[button1 addTarget:self action:@selector(click1:) forControlEvents:UIControlEventTouchUpInside];
button1.tag = 1;
// UIView 遮挡层 模拟键盘遮挡
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 667-260, 375, 260)];
view.backgroundColor = [UIColor greenColor];
[self.view addSubview:view];
view.tag = 7;
}
- (void)click:(UIButton*)btn{
UIView* view = (UIView*)[self.view viewWithTag:7];
// UIView的动作效果
[UIView animateWithDuration:1 animations:^{
// 下降效果 原因:把y由原来的667-260 变成667 因此UIView整个在屏幕下面
view.frame = CGRectMake(0, 667, view.frame.size.width,view.frame.size.height);
// 把下面的按钮的位置改变为view上面50的高度
if (1 == btn.tag) {
CGRect btnFrame = btn.frame;
btnFrame.origin = CGPointMake(btn.frame.origin.x,self.view.frame.origin.y-view.frame.origin.y);
btn.frame = btnFrame;
NSLog(@"%@",btn.frame);
}
}];
}
- (void)click1:(UIButton*)btn{
static BOOL flg=YES;
if (flg) {
[UIView animateWithDuration:1 animations:^{
// 传进来view
UIView *view=(UIView *)[self.view viewWithTag:7];
// view的y == 屏幕-遮挡的高度 view.y等于view的高度
view.frame=CGRectMake(0, 667-260, view.frame.size.width, view.frame.size.height);
// btn的 y == 300 其他的位置大小不变
UIButton *button=(UIButton *)[self.view viewWithTag:1];
button.frame=CGRectMake(button.frame.origin.x,300, button.frame.size.width, button.frame.size.height);
}];
flg=NO;
}else{
// view的y == 屏幕-遮挡的高度 view.y等于view的高度
[UIView animateWithDuration:1 animations:^{
UIView *view=(UIView *)[self.view viewWithTag:7];
view.frame=CGRectMake(0, 667, view.frame.size.width, view.frame.size.height);
UIButton *button=(UIButton *)[self.view viewWithTag:1];
button.frame=CGRectMake(button.frame.origin.x,500, button.frame.size.width, button.frame.size.height);
}];
flg=YES;
}
}
@end