gpt4 book ai didi

ios - 带有 subview 的编程 UIView 未在正确位置呈现

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:12 24 4
gpt4 key购买 nike

我正在尝试呈现其中包含 subview 的 View 。但是, subview 在不正确的 y 位置呈现。

ViewController 是父 View 。

ViewController2ViewController 的 subview ,并且有自己的 subview (我们称它为 X)。 X 在错误的 y 位置呈现,即使 ViewController2X 的帧具有相同的 y 值。

编辑:我应该注意,X 应该出现在 ViewController2 中的相同位置。或者至少,这是意图。

见下面的代码:

ViewController.swift

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

var y: CGFloat = 10

for vc in getVcs() {
self.view.addSubview(vc.render(x: 10, y: y))
y += 75
}

super.viewDidLoad()
}

func getVcs() -> [ViewController2] {
return [
ViewController2(),
ViewController2(),
ViewController2()
]
}
}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

func render(x: CGFloat, y: CGFloat) -> UIView {
let viewFrame = CGRect(x: x, y: y, width: 300, height: 50)
let xview = UIView(frame: viewFrame)

let subViewFrame = CGRect(x: x, y: y, width: 200, height: 25) // X
let subView = UIView(frame: subViewFrame)
subView.layer.borderColor = UIColor.green.cgColor
subView.layer.borderWidth = 1
xview.addSubview(subView)

xview.layer.borderColor = UIColor.red.cgColor
xview.layer.borderWidth = 1
return xview
}

}

它们在运行时如何出现:

(绿色边框代表X,红色边框代表ViewController2。)

enter image description here

如有任何帮助,我们将不胜感激!

最佳答案

一个 View 定义了它自己的与其父 View 相关的框架。

在 ViewController2 中,您根据 y 参数实例化的 subview 将相对于其父 View (红框)添加。

解决方案是更改 subview 框架上相对于父框架的 y 值

let subViewFrame = CGRect(x: x, y: y, width: 200, height: 25) // X

另外,为了清楚地了解发生了什么,尝试在 getVCs() 中添加另一个 ViewController2(),它看起来像这样。

如您所见,您的代码并没有将第二个 View 放错位置,就像您的屏幕截图中显示的那样。它将绿色框放置得离其父框架越来越远。第三帧只是一个幸运的命中。希望这有帮助 =)

enter image description here

关于ios - 带有 subview 的编程 UIView 未在正确位置呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41527701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com