gpt4 book ai didi

ios - 为什么UIView会填充superView?

转载 作者:行者123 更新时间:2023-11-29 05:56:13 25 4
gpt4 key购买 nike

我正在以编程方式创建一个 subview ,我希望将其放置在 super View 上,但我不希望它填充输入 super View 。

我一直在检查这个问题是否曾被问过,但由于某种原因,我只能找到如何填充整个 View 的答案。

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

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 构建在一个单独的文件中,我不确定是否需要它的信息,因为它只是 subview 内部的内容。

最佳答案

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

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()

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

关于ios - 为什么UIView会填充superView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55135027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com