gpt4 book ai didi

ios - 自定义 View 未正确显示

转载 作者:行者123 更新时间:2023-11-28 13:42:20 26 4
gpt4 key购买 nike

我试图在 iOS 屏幕上显示 3 个自定义 View ,但只显示其中一个。第二个在放置大量 constraints 后开始以不正确的方式出现,第三个完全没有出现。为了测试,我调用了同一个 View 三次。请参阅代码。我刚开始做 iO,所以如果我犯了任何错误或明显的错误,请原谅我。

我试图相应地设置约束,在后面放一个 ScrollView ,但这些似乎都不起作用

I am getting this result Here is storyboard screenshot and constraints

我从 storyboard 中删除了 container3,因为当我添加它时,container2 甚至没有出现。请帮我解决这个布局问题。

class TestCustomViewController: UIViewController {

@IBOutlet weak var container : UIView?

@IBOutlet weak var container2 : UIView?

@IBOutlet weak var container3 : UIView?

var testView: CustomView!
var testView2: CustomView!
var testView3: CustomView!
override func viewDidLoad() {
super.viewDidLoad()
////////First View//////
testView = createGearItemView()
testView.frame = (container?.frame)!
container?.addSubview(testView)
/////////Second View//////
testView2 = createGearItemView()
testView2.frame = (container2?.frame)!
container2?.addSubview(testView2)
////// THird View/////////
testView3 = createGearItemView()
testView3.frame = (container3?.frame)!
container3?.addSubview(testView3)
}

func createGearItemView () -> CustomView {
let view = (Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView)!

view.backgroundColor = UIColor.clear
return view
}

}

最佳答案

除了您应该熟悉自动布局(参见 Understanding Auto Layout)之外,您必须使用容器的 bounds 作为 subview 的 frame(尽管在 viewDidLoad 中它可能不是正确的):

testView.frame = (container?.bounds)!
...

更好的方法是为您的 subview 使用自动布局,而不是直接设置 frame:

testView = createGearItemView()
container?.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
testView.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true
testView.leadingAnchor.constraint(equalTo: container!.leadingAnchor).isActive = true
testView.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true
testView.trailingAnchor.constraint(equalTo: container!.trailingAnchor).isActive = true
testView2...

关于ios - 自定义 View 未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862470/

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