能写一些代码,但是对代码底层的机制并不了解,所以经常导致遇到莫名其妙的问题。今天遇到的问题是,我写了3个scrollView,把它们的位置设定好了,只是装到了stackView里,并让它们等间距排列,但是它们却不显示了,代码如下:
let aiScrollView.frame = CGRect(x: 10, y: view.frame.size.height - 315, width: view.frame.size.width - 20, height: 52)
let yinfuScrollView = UIScrollView(frame: CGRect(x: 10, y: view.frame.size.height - 255, width: view.frame.size.width - 20, height: 50))
let secondScrollView = UIScrollView(frame: CGRect(x: 10, y: view.frame.size.height - 195, width: view.frame.size.width - 20, height: 50))
let stackView = UIStackView(arrangedSubviews: [aiScrollView, yinfuScrollView, secondScrollView])
view.addSubview(stackView) // 要先添加子视图再写约束
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -0).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 272).isActive = true
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.spacing = 5 // 最小间距
我了解了一下stackView的用法,说若是要用equalSpacing这个属性,必须要给每个子view添加约束,我一直不理解什么是约束,我觉得我都把每个子view的位置都写死了,这难道还不叫约束吗?
后来我找到了解决办法,应该在每个子view后面加上这样一句(以aiScrollView为例):
aiScrollView.heightAnchor.constraint(equalToConstant: 52).isActive = true
问题就解决了,原来这个语句才叫约束,那之前写的那个位置语句叫什么呢?不知道,不管了,现在编程语言太复杂了,普通人已经没办法掌握的那么精通了。