【问题标题】:Issue with programmatic added views程序化添加视图的问题
【发布时间】:2017-02-27 14:29:33
【问题描述】:

嗨,我正在以编程方式添加一些这样的视图

        let xPos = (self.view.frame.size.width - 200)/2
        self.headerLabel = UILabel(frame: CGRect(x: xPos, y: 50.0, width: 200.0, height: 100.0))
        self.shopButton = UIButton(frame: CGRect(x: xPos, y: 150.0, width: 200.0, height: 40.0))
        self.createButton = UIButton(frame: CGRect(x: xPos, y: 230.0, width: 200.0, height: 40.0))
        self.orLabel = UILabel(frame: CGRect(x: xPos, y: 200.0, width: 200.0, height: 20.0))

问题是当我将设备旋转到横向模式时,反之亦然,我的视图与左侧对齐。如何预防?

【问题讨论】:

标签: ios swift views programmatically-created


【解决方案1】:

使用NSLayoutConstaint将视图中的约束添加到其超级视图

例如

let horizontalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerX, relatedBy: .equal, toItem: view.superview, attribute: .centerX, multiplier: 1, constant: 1)
        horizontalConstraint.isActive = true

        let verticalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerY, relatedBy: .equal, toItem: view.superview, attribute: .centerY, multiplier: 1, constant: 1)
        verticalConstraint.isActive = true

【讨论】:

    【解决方案2】:

    如果可以的话,我会在界面构建器中添加这些元素。然后,您可以手动设置约束,这比以编程方式添加它们要容易得多。您看到此行为的原因是因为您的元素没有约束,因此当屏幕旋转时它们不会改变方向。

    查看以下链接: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html

    https://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2

    【讨论】:

      【解决方案3】:

      如果您根本不使用 Storyboard,我建议您使用 Neon 框架。 它可以帮助您以编程方式设计整个视图 - 并在其上放置按钮、图像……。

      请参阅以下 Github 存储库: https://github.com/mamaral/Neon

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多