【问题标题】:How to write the manual AutoLayout constraint?如何编写手动 AutoLayout 约束?
【发布时间】:2016-11-16 09:35:52
【问题描述】:

我是一名新手 iOS 开发人员,我想学习如何编写手册 AutoLayout 约束。正如我发现的那样,该链接在视觉上允许AutoLayout 如何工作。请参考以下链接了解更多信息。

网址:https://autolayoutconstraints.com/

但是它不允许当其他组件在那里以及它们的关系时它是如何工作的。

感谢您如此迅速的回复,我希望我能更清楚地了解我的问题。

【问题讨论】:

    标签: autolayout xcode8 ios10


    【解决方案1】:

    我想你所说的手动是指通过代码应用约束。

    自问世以来,自动版式一直在不断发展。 要通过代码应用约束,您可以使用这三种技术中的任何一种。 (底部最简单最新的技术)

    旧的详细约束使用方法,(constraintWithItem)

    +(instancetype)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(nullable id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c
    

    视觉格式语言 (https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html)

    布局锚点 (https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW5)

    您可以谷歌粗体的以了解更多信息。 但是这些都没有比https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/index.html#//apple_ref/doc/uid/TP40010853-CH7-SW1更好的了 本文档包含应用约束的示例,以及其他组件(视图)及其关系。

    【讨论】:

      【解决方案2】:

      您是否在询问如何以编程方式设置约束?如果是,您打算完全使用故事板还是以编程方式实现所有内容?

      如果你想以编程方式完成这一切,它看起来像:

      class someViewController: UIViewController{
          let myLabel: UILabel = {
              let label = UILabel()
              label.translatesAutoresizingMaskIntoConstraints = false
              label.text = "Hello"
          }
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              view.addSubView(myLabel)
      
              myLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
              myLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
              myLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
              myLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
          }
      }
      

      这将在您的 ViewController 中创建一个标签,并将其固定在左侧和底部,设置高度为 50 像素。您可以通过查找它的锚并将其设置为所需的值来找到该项目的任何一个约束。确保将 translatesAutoresizingMaskIntoConstraints 设置为 false,否则将不会遵循您的约束。

      【讨论】:

        【解决方案3】:

        您可以使用第 3 方库,例如 SnapkitSwiftyLayout

        【讨论】:

          猜你喜欢
          • 2014-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-21
          • 1970-01-01
          • 1970-01-01
          • 2016-12-15
          • 2015-12-16
          相关资源
          最近更新 更多