python实现范围框跟随_输入框跟随键盘移动效果的实现

inputAccessoryView : 系统自带的键盘上面的工具条视图(并没有什么卵用)

由于系统自带的工具条随着键盘的隐藏也一起隐藏了,而现在很多应用的需求的是键盘隐藏工具条停留在最底部,所以我们需要自定义工具条(或者说输入框吧),具体效果如图所示:

方式一:修改约束 constant 方式

这种方式需要在storyboard或xib中找到输入框和父控件(控制器)的约束,代码中的self.bottomConstraint就是该约束,我们通过监听键盘的弹出和收回来更改约束的值,再加点动画效果,就是这么简单

- (void)viewDidLoad {

[super viewDidLoad];

// 监听键盘改变

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

// 移除监听

- (void)dealloc{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

// 监听键盘的frame即将改变的时候调用

- (void)keyboardWillChange:(NSNotification *)note{

// 获得键盘的frame

CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

// 修改底部约束

self.bottomConstraint.constant = self.view.frame.size.height - frame.origin.y;

// 执行动画

CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

[UIView animateWithDuration:duration animations:^{

// 如果有需要,重新排版

[self.view layoutIfNeeded];

}];

}

方式二:transform 方式

此方式大部分代码和上面是一样的,只不过这次我们不是修改constant了,而是通过transform方式修改输入框 键盘隐藏 和 键盘显示 时 两者y 的 差值(一定要断好句)

/**

* 设置输入框

*/

- (void)setUpToolbar{

BSPostWordToolbar *toolbar = [BSPostWordToolbar viewFromXib];

toolbar.width = self.view.width;

toolbar.y = BSScreenH - toolbar.height;

// 添加通知监听键盘的弹出与隐藏

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

[self.view addSubview:toolbar];

self.toolbar = toolbar;

}

- (void)dealloc{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)keyboardWillChangeFrame:(NSNotification *)notification{

// 拿到键盘弹出时间

double duration = [notification.userInfo[

UIKeyboardAnimationDurationUserInfoKey

] doubleValue];

// 计算transform

CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;

CGFloat ty = keyboardY - BSScreenH;

/**

* 像这种移动后又回到原始位置的建议使用transform,因为transform可以直接清零回到原来的位置

*/

[UIView animateWithDuration:duration animations:^{

self.toolbar.transform = CGAffineTransformMakeTranslation(0, ty);

}];

}

更多关于iOS学习开发的文章请登陆我的个人博客www.zhunjiee.com,欢迎前来参观学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值