iOS 自动布局结果不正确

标签 ios swift autolayout

我有一个自定义 View ,其中有两个 subview ,它们平分其 super View 。我想要如下所示的自定义 View :

-------------------------------
|              |              |
|             300             |
|              |              |
|-----------------------------|
|    red       |     green    |
|-----------------------------|
|                             |

但是,无论我修改约束,结果总是如下所示:

-------------------------------
|    red       |     green    |
|-----------------------------|
|                             |

自定义 View 的框架是正确的,为(0, 300, 375, 60)。但其 subview 的原点始终为 (0, -300)。

RootController.swift

override func viewDidLoad() {
  super.viewDidLoad()

  let view = RootView()
  view.translatesAutoresizingMaskIntoConstraints = false
  self.view.addSubview(view)
  self.rootView = view

  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "V:|-300-[v(60)]", metrics: nil, views: ["v": self.rootView!]),
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[v]|", metrics: nil, views: ["v": self.rootView!])
  ].flatMap({ $0 }))
}

RootView.swift

override init (frame: CGRect) {
  super.init(frame: frame)

  var view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .red
  self.addSubview(view)
  self.red = view

  view = UIView()
  view.translatesAutoresizingMaskIntoConstraints = false
  view.backgroundColor = .green
  self.addSubview(view)
  self.green = view
}

override func updateConstraints () {
  NSLayoutConstraint.activate([
    NSLayoutConstraint.constraints(withVisualFormat: "H:|[r][g(==r)]|", metrics: nil, views: ["r": self.red, "g": self.green])
  ].flatMap({ $0 }))
  NSLayoutConstraint.activate([
    self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.green.heightAnchor.constraint(equalTo: self.heightAnchor)
  ])
  super.updateConstraints()
}

最佳答案

我错过了一个垂直约束,如下所示:

override func updateConstraints () {
  // ...

  NSLayoutConstraint.activate([
    self.red.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.green.heightAnchor.constraint(equalTo: self.heightAnchor),
    self.red.topAnchor.constraint(equalTo: self.topAnchor),
    self.green.topAnchor.constraint(equalTo: self.topAnchor)
  ])

  // ...
}

这将解决我的问题。

关于iOS 自动布局结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247593/

相关文章:

ios - RXswift,重复可观察直到完成

ios - 在哪里设置 CGAffineTransformMakeScale(2, 2);

ios - 在 webrtc 回调 "- (void)peerConnectionOnRenegotiationNeeded:(RTCPeerConnection *)peerConnection"中应该做什么?

ios - 如何将字符串值转换为枚举

ios - UILabel 上的 SizeToFit 和自动布局

iphone - iOS 5 上的应用程序崩溃 - 无法实例化名为 NSLayoutConstraint 的类

iphone XMPP App运行后台

ios - iOS 11 Swift 下面的 UITabBar 转换问题

ios - 使用自动布局时,UIButton 中的图像不会缩放。

swift - 在 Swift 闭包中隐式使用 self