ios - 以编程方式添加 View 的问题

标签 ios swift view programmatically-created

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

        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))

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

最佳答案

使用NSLayoutContaint将 View 中的约束添加到其 super View

例如

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

关于ios - 以编程方式添加 View 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488253/

相关文章:

ios - swift 4.2 枚举案例 ' ' 在类型 '?' 中找不到 switch 语句中的要求以冗余解包隐式解包的可选

ios - fatal error : unexpectedly found nil while unwrapping an Optional value (Swift & Parse)

ios - UIDatePicker 值与显示的日期不匹配

android - horizo​​ntalscrollview - onScroll?

php - 如何访问 Blade View laravel 5.6 中定义的关系

ios - 在后台播放音乐并切换 View

ios - Xcode 5 Assets 目录 : What is "Default" image set

asp.net-mvc - 如何在View中获取当前url值

ios - 将观察者添加到自定义 tableview 单元格中的 UISwitch

ios - 带有与 ViewController 分离的 Controller 的 UITableView