为什么UIView会填充superView?

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

我正在以编程方式创建一个子视图,我希望将其定位在superView上,但我不希望它填充输入superView。

我一直在检查是否有问过这个问题,但出于某种原因,我只能找到如何填写整个视图的答案。

如果有人可以帮助批评我的代码并解释如何定位subView而不是填充整个superview,我将非常感激。

class JobViewController: UIViewController {
    var subView : SubView { return self.view as! SubView }
    var requested = false

    let imageView: UIImageView = {
        let iv = UIImageView(image: #imageLiteral(resourceName: "yo"))
        iv.contentMode = .scaleAspectFill
        iv.isUserInteractionEnabled = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)
        imageView.fillSuperview()

        subView.requestAction = { [ weak self ] in
            guard let strongSelf = self else { return }
            strongSelf.requested = !strongSelf.requested
            if strongSelf.requested {
                UIView.animate(withDuration: 0.5, animations: {
                    strongSelf.subView.Request.setTitle("Requested", for: .normal)
                    strongSelf.subView.contentView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
                })
            } else {
                UIView.animate(withDuration: 0.5, animations: {
                    strongSelf.subView.Request.setTitle("Requested", for: .normal)
                    strongSelf.subView.contentView.backgroundColor = UIColor.blue
                })
            }
        }
    }

    override func loadView() {
     // I know the issue lies here, but how would I go about setting the frame of the subview to just be positioned on top of the mainView?
        self.view = SubView(frame: UIScreen.main.bounds)
    }
}

我将subView内置在一个单独的文件中,我不确定我是否需要它的信息,因为它只是在子视图内部。

ios swift uiviewcontroller subview
1个回答
0
投票

您应该将subView添加为self.view的子视图,而不是将其设置为与主视图相同。然后相应地设置约束。

override func viewDidLoad() {
    self.view.addSubview(subView)
    subview.translatesAutoresizingMaskIntoConstraint = false
    addSubview.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
    addSubview.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
    addSubview.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
    addSubview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
}

关于您的初始化问题,请尝试:

var subView = SubView()

我希望我理解你的问题是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.