添加到子视图的UI按钮崩溃了应用程序swift

问题描述 投票:0回答:1

我创建了一个UIButton,我想直接添加到另一个在storyboard中创建的UI按钮的顶部。我以编程方式添加了创建的一个,但它崩溃了应用程序。

var routeButton: UIButton!
override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(routeButton)
        setupRouteBtn()
    }

fileprivate func setupRouteBtn() {

        routeButton = UIButton(type: .custom)
        routeButton.backgroundColor = UIColor.flatBlack()
        routeButton.translatesAutoresizingMaskIntoConstraints = false
        routeButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
        routeButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

        //        routeBtn.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 10).isActive = true
        //        routeBtn.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -10).isActive = true

        routeButton.trailingAnchor.constraint(equalTo: fab.trailingAnchor).isActive = true
        routeButton.leadingAnchor.constraint(equalTo: fab.leadingAnchor).isActive = true
        routeButton.bottomAnchor.constraint(equalTo: fab.topAnchor).isActive = true

        routeButton.setNeedsLayout()
        routeButton.layoutIfNeeded()
        routeButton.layer.cornerRadius = 0.5 * routeButton.bounds.size.width
        routeButton.setImage(UIImage(named:"Group-3.png"), for: .normal)
        routeButton.imageView?.contentMode = .scaleAspectFit
        routeButton.clipsToBounds = true
    }
ios swift
1个回答
0
投票

当你将它添加为子视图时,你的routeButton变量是nil。您需要在将其添加为子视图之前进行分配

var routeButton = UIButton(type: .custom)

...然后不要在setupRouteBtn中分配它

routeButton = UIButton(type: .custom)


var routeButton = UIButton(type: .custom)

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(routeButton)
    setupRouteBtn()
}

fileprivate func setupRouteBtn() {
    routeButton.backgroundColor = .flatBlack()
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.