zoukankan      html  css  js  c++  java
  • 代码手动修改约束(AutoLayout)

    当使用xib或storyBoard构建项目,并使用了AutoLayout之后,当需要为视图添加动画,或者手动更改视图的frame的时候,就需要修改约束啦.别以为代码中修改约束很麻烦,其实还蛮简单的啦.

    例如: 跟随键盘弹出的ToolBar,原来在视图底部,当键盘弹出时,ToolBar跟随键盘弹出

    • 首先将ToolBar到底部的约束添加一个IBOutlet
    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolViewBottomConstraint;
    • 键盘弹出修改约束
    //键盘的通知(显示)
    - (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];
    }

    下面来看下,如何删除和增加约束 最后,附个addConstraint 函数的意义: view1.attr1 = view2.attr2 * multiplier + constant

     [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重新添加一个约束



    文/好好姐(简书作者)
    原文链接:http://www.jianshu.com/p/5ae4d59abc4a
    著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
  • 相关阅读:
    (数据科学学习手札21)sklearn.datasets常用功能详解
    (数据科学学习手札20)主成分分析原理推导&Python自编函数实现
    (数据科学学习手札19)R中基本统计分析技巧总结
    (数据科学学习手札18)二次判别分析的原理简介&Python与R实现
    P2633|主席树+dfs序+树链剖分求lca+离散化
    主席树|求区间第k小模板
    树上问题
    数据结构|序列问题与树上问题小结
    珂朵莉树 例题小结
    CF#609E|二分+树状数组
  • 原文地址:https://www.cnblogs.com/gaohe/p/5799605.html
Copyright © 2011-2022 走看看