自定义视图未正确显示

时间:2019-04-26 07:07:43

标签: ios swift layout

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

我试图相应地施加约束,在其后放置一个滚动视图,但这似乎都不起作用

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
}

}

1 个答案:

答案 0 :(得分:1)

除了您应该熟悉自动版式(请参见Understanding Auto Layout)之外,您还必须将容器的bounds用作frame的子视图(尽管可能不这样做)是viewDidLoad中的正确词):

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

一种更好的方法是对子视图使用自动版式,而不是直接设置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...