【发布时间】:2021-10-22 12:32:47
【问题描述】:
我可以通过以下方式在 iOS 14 中轻松创建一个带有圆角的 stackview:
stackView.layer.cornerRadius = 10
stackView.clipsToBounds = true
没有做任何其他事情。但是由于我希望我的应用程序也可以在不能超越 iOS 12 的 iPhone 6 上运行,所以上面的 2 行代码没有任何作用。我查看了How can I set the cornerRadius of a UIStackView? 并将代码改编为我的应用程序,但它仍然无法正常工作。明确地说,我有:
- 更改了我的构建设置以使用 iOS 12.3 的部署目标
- 排除了对场景的引用并添加了窗口变量 (Add iOS 12 support to a new Xcode 11 Project)
- 使用 iPhone 11 和 iphone 6 模拟器测试(均未显示圆角)
这是我的代码:
import UIKit
class ViewController: UIViewController {
let buttonList = ["Dog", "Cat", "Mouse"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = 6
stackView.backgroundColor = .systemPink // this actually works
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.widthAnchor.constraint(equalToConstant: 140).isActive = true
// The following is "supposed" to create rounded corners for the stackview
let subView = UIView(frame: stackView.bounds)
subView.backgroundColor = .yellow // this ends up showing through instead of the systemPink
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
stackView.insertSubview(subView, at: 0)
subView.layer.cornerRadius = 10
subView.layer.masksToBounds = true
subView.clipsToBounds = true
// Fill the stackview with buttons
for index in 0..<buttonList.count {
let button = UIButton()
button.setTitle(buttonList[index], for: .normal)
button.backgroundColor = .cyan
button.setTitleColor(.black, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
stackView.addArrangedSubview(button)
}
}
}
这就是它的样子(没有圆角):
那么我错过了什么?对于 iPhone 6 (iOS 12) 及更高版本,如何使我的 stackview 看起来有圆角?
【问题讨论】:
标签: swift uistackview rounded-corners ios12