所以我将以下UIKit元素添加到我的UIViewController中以控制出现的模拟。我希望不得不写很多放置代码,但是所有设备看起来完全没有任何设备...我的问题是为什么?
let menuButton = UIButton()
let statusLabel = UILabel()
let segmentedLabel = UISegmentedControl(items: ["None", "Glow", "Cloud"])
func initializeUI() {
//The menu button that opens up the options for the simulations
menuButton.layer.borderColor = UIColor.lightGray.cgColor
menuButton.layer.borderWidth = 1
menuButton.layer.cornerRadius = 5
menuButton.layer.backgroundColor = UIColor.darkGray.cgColor
menuButton.showsTouchWhenHighlighted = true
menuButton.imageView?.contentMode = UIViewContentMode.scaleAspectFit
menuButton.setImage(UIImage(named: "hamburger.png"), for: UIControlState.normal)
menuButton.addTarget(self, action: #selector(menuPress), for: UIControlEvents.touchDown)
view.addSubview(menuButton)
//Will display the status of the simulation
statusLabel.text = "Particle Simulation"
statusLabel.textColor = UIColor.darkGray
view.addSubview(statusLabel)
//Will display visual options
view.addSubview(segmentedLabel)
}
每个元素的大小都很完美,它们不重叠。标签位于左下角,按钮位于右下方,分段视图位于左上角(我的横向应用程序)。
我还有一个问题是,如果我想以编程方式开始放置这些对象,我该怎么做?这些元素没有我可以使用的属性位置,如果我执行menuButton.frame.size.height *= 20
之类的操作,则不会使菜单按钮超高。
答案 0 :(得分:0)
这样做的原因是您示例中的所有UI项目都具有“内在”内容大小,因此他们可以创建自己的框架。以同样的方式添加标准UIView,你将失去运气。此外,视图使用自动调整大小掩码(也称为弹簧和支柱)基于初始帧创建自己的约束。
最后放置项目,直接设置框架。只是数学。祝好运。
了解内在内容大小非常重要。某些帧更改可能需要您关闭自动约束,但通常情况并非如此,但可能是您的按钮出现问题
UIView.translatesAutoresizingMaskIntoConstraints = false