UIButton在ContainerView之外

时间:2017-05-03 01:40:00

标签: swift

我是Swift的新手,我正在努力学习如何以编程方式构建iOS应用,而故事板的使用非常有限。现在,目标是在应用程序的顶部创建一个菜单,其中包含按钮。基于我的研究,似乎最好的方法是将UIButtons嵌套在ContainerView中。但是,问题是我的UIButton显示在ContainerView之外。也许我需要在ViewContainer和我的UIButton上设置约束?

请你指点我正确的方向吗?非常感谢您的帮助。

故事板:

enter image description here

App Simulator(iPhone 7 Plus):

enter image description here

HomeController.swift:

class HomeController: UIViewController {
    let topMenuContainerView = UIView()
    topMenuContainerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(topMenuContainerView)

    let topMenuController = storyboard!.instantiateViewController(withIdentifier: "Top_Menu_View_Controller")
    addChildViewController(topMenuController)
    topMenuController.view.translatesAutoresizingMaskIntoConstraints = false

    topMenuContainerView.addSubview(topMenuController.view)
    topMenuController.didMove(toParentViewController: self)
}

TopMenuController.swift:

class TopMenuController: UIViewController {
    let createAdButton: UIButton = UIButton(type: UIButtonType.roundedRect)

    createAdButton.setTitle("Create Ad", for: UIControlState.normal)
    createAdButton.titleLabel?.textColor = UIColor.white
    createAdButton.frame = view.frame
    createAdButton.backgroundColor = UIColor.white

    view.addSubview(createAdButton)
}

1 个答案:

答案 0 :(得分:1)

是的,我相信添加约束可以解决您的问题。它会是这样的:

let horizontalConstraint = NSLayoutConstraint(item: createAdButton, attribute: NSLayoutAttribute.centerX, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: createAdButton, attribute: NSLayoutAttribute.centerY, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

view.addConstraints([horizontalConstraint, verticalConstraint])

但是,在家庭控制器中只有一个UIView而不是仅用于菜单的View Controller会不会更好?