【问题标题】:How to change the UI layout with code that has used Auto Layout in Swift?如何使用在 Swift 中使用 Auto Layout 的代码更改 UI 布局?
【发布时间】:2014-10-27 02:33:19
【问题描述】:

我有一个使用自动布局的登录视图。当我单击用户名文本文件输入一些信息时,视图会弹出键盘,然后键盘会阻止一些 UI。我想在代码中弹出键盘时更改一些 UI 的框架信息,但是由于 UI 使用自动布局,所以在代码中设置 UI 的框架不起作用。

我应该如何处理这种情况?

【问题讨论】:

    标签: ios xcode swift autolayout


    【解决方案1】:

    您应该为要修改的约束创建一个 IBOutlet,并在代码中更改(如果需要动画)其常量属性的值。

    【讨论】:

      【解决方案2】:

      您需要为NSLayoutConstraint 的常量值设置动画。

      所以你创建一个这样的:

      class ViewController: UIViewController {
      
          var loginBox:UIView?;
          var loginBoxTopConstraint:NSLayoutConstraint?;
      
          override func viewDidLoad() {
      
              ...
      
              self.initConstraints();
      
          }
      
          func initConstraints()
          {
              // init constraints here
          }
      
          ...
      
      }
      

      然后你将约束初始化为这样的:

      func initConstraints()
      {
      
          ...
      
          self.loginBoxTopConstraint = NSLayoutConstraint(item: self.loginBox!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 150.0);
      
          self.view.addConstraint(self.loginBoxTopConstraint!);
      }
      

      现在,当您的用户点击您的登录字段之一时,您的 UITextField 委托 didBeginEditing 会被调用。这是您为约束常量值设置动画的地方:

      func textFieldDidBeginEditing(textField: UITextField) {
      
          ...        
      
          self.loginBoxTopConstraint?.constant = 20.0; // was 150 before
      
          UIView.animateWithDuration(0.5, animations: { () -> Void in
      
              self.view.layoutIfNeeded();
      
          });
      
      }
      

      当用户完成输入文本字段时,应该调用 textFieldDidEnd 委托方法:

      func textFieldDidEndEditing(textField: UITextField) {
      
          ...
      
          self.loginBoxTopConstraint?.constant = 150.0; // reset to 150
      
          UIView.animateWithDuration(0.5, animations: { () -> Void in
      
              self.view.layoutIfNeeded();
      
          });
      
      }
      

      希望对您有所帮助。

      【讨论】:

      • 非常感谢!我已经在 Storyboard 中设置了约束,所以在 initConstraints 函数中应该获取 loginBox 的约束,而不是创建并添加一个约束,对吧?如何获取 loginBox 的约束?
      • 不,你需要像我上面展示的那样声明和使用 NSLayoutConstraint 属性。您在情节提要中指定的约束是固定约束,它们不是可动画的。
      • 情节提要中的约束不固定,这是错误的。您可以像在代码中创建的那样修改它们。
      • 那么,我如何在代码中获得使用故事板制作的约束?
      • 在 ViewController 中创建了一个常量 IBOutLet?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2015-02-12
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多