键盘和输入框上移

这篇博客探讨了如何在移动应用中实现键盘弹出时,输入框和视图伴随键盘一起平滑上移的动画效果,同时提到了状态栏的隐藏设置,尤其适用于小说阅读场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动画和键盘一起向上平移

定义两个属性

@property(nonatomic,retain)UITextField *textField;
@property(nonatomic,retain)UIView *myView;

创建输入框和view

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor cyanColor];
    self.myView=[[UIView alloc] initWithFrame:CGRectMake(100, 600, 200, 50)];
    self.myView.backgroundColor=[UIColor orangeColor];
    [self.view addSubview:self.myView];

    self.textField=[[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
    self.textField.backgroundColor=[UIColor redColor];
    [self.view addSubview:self.textField];

    //监听键盘的弹起和回收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];

}
//键盘弹起的时候触发的方法
-(void)keyBoardAppear:(NSNotification *)notification{
    NSLog(@"键盘弹起了");
    //找到键盘的尺寸
    CGRect rect=[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
   //整体打印结构体的方法
    NSLog(@"%@",NSStringFromCGRect(rect));
    //用UIView的动画,让视图随键盘向上平移
    [UIView animateWithDuration:0.2 animations:^{
        self.myView.frame=CGRectMake(100, 600-rect.size.height, 200, 50);
    }];
}
//键盘回收时触发的方法
-(void)keyBoardWillHidden:(NSNotification *)notification{
//    CGRect rect=[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:0.2 animations:^{
        self.myView.frame=CGRectMake(100, 600, 200, 50);
    }];
}
//点击空白回收键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.textField resignFirstResponder];

}
//9.0之后,修改状态栏(显示时间,电量,运营商的那行)方法发生了变化,需要在当前要修改的viewController里重写方法
-(UIStatusBarStyle)preferredStatusBarStyle{
   return  UIStatusBarStyleLightContent;
}

是否隐藏状态栏(该功能多用于小说页面)

-(BOOL)prefersStatusBarHidden{
    return NO;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值