为什么UIView会填充superView?

Why does UIView fill the superView?

我正在以编程方式创建一个子视图,我希望它位于 superView 之上,但我不希望它填充输入 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)
    }
}

我在一个单独的文件中构建了我的子视图,我不确定我是否需要它的信息,因为它正是子视图内部的内容。

您应该将您的子视图添加为 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()

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