当使用xib或storyBoard构建项目,并使用了AutoLayout之后,当需要为视图添加动画,或者手动更改视图的frame的时候,就需要修改约束啦.别以为代码中修改约束很麻烦,其实还蛮简单的啦.
例如: 跟随键盘弹出的ToolBar,原来在视图底部,当键盘弹出时,ToolBar跟随键盘弹出
<li>首先将ToolBar到底部的约束添加一个IBOutlet</li>
<pre><code>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolViewBottomConstraint;
</code></pre>
<li>键盘弹出修改约束</li>
<pre><code>
//键盘的通知(显示)
-
(void)keyboardWillShow:(NSNotification )notification
{
NSValue aValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
NSNumber *durationValue = [notification userInfo][UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration = durationValue.doubleValue;[UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
_toolViewBottomConstraint.constant = keyboardRect.size.height;//修改距离底部的约束
} completion:^(BOOL finished) {
}];
[self.view setNeedsLayout]; //更新视图
[self.view layoutIfNeeded];
}
</code></pre>
下面来看下,如何删除和增加约束
最后,附个addConstraint 函数的意义:
view1.attr1 = view2.attr2 * multiplier + constant
<pre><code>
[self.view removeConstraint:_sinaLeftDistance];//在父试图上将iSinaButton距离屏幕左边的约束删除
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:iSinaButton //子试图
attribute:NSLayoutAttributeCenterX //子试图的约束属性
relatedBy:NSLayoutRelationEqual //属性间的关系
toItem:self.view//相对于父试图
attribute:NSLayoutAttributeCenterX//父试图的约束属性
multiplier:1.0
constant:0.0];// 固定距离
[self.view addConstraint: myConstraint];//为iSinaButton重新添加一个约束
</code></pre>
网友评论
* 当键盘改变了frame(位置和尺寸)的时候调用
*/
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
// 设置窗口的颜色
self.view.window.backgroundColor = self.tableView.backgroundColor;
// 0.取出键盘动画的时间
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// 1.取得键盘最后的frame
CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 2.计算控制器的view需要平移的距离
CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
NSLog(@"transformY=%f,keyboardFrame.origin.y = %f self.view.frame.size.height = %f",transformY,keyboardFrame.origin.y,self.view.frame.size.height);
// 3.执行动画
[UIView animateWithDuration:duration animations:^{
_bottomLayout.constant = transformY;
}];
[self.view setNeedsLayout]; //更新视图
[self.view layoutIfNeeded];
}
大神看我这么写 如何不对