我有一个符合UIView的自定义类。它包含一个UIPickerView和UIButton。我使用以下代码:
class ColorPickerView: UIView {
// MARK: - Subviews
private lazy var colorPicker: UIPickerView = {
let picker = UIPickerView()
picker.translatesAutoresizingMaskIntoConstraints = false
picker.dataSource = self
picker.delegate = self
picker.isHidden = false
return picker
}()
private lazy var colorSave: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Save", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = false
button.backgroundColor = .black
button.addTarget(self, action: #selector(didTapColorSave), for: .touchUpInside)
return button
}()
// MARK: - Lifecycle
init() {
super.init(frame: .zero)
addSubviews()
setupConstraints()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Actions
@IBAction func didTapColorSave(sender: AnyObject) {
hideUI()
}
// MARK: - Private
private func addSubviews() {
self.isUserInteractionEnabled = false
addSubview(colorSave)
addSubview(colorPicker)
}
private func setupConstraints() {
NSLayoutConstraint.activate([
colorSave.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
colorSave.topAnchor.constraint(equalTo: bottomAnchor, constant: -64),
colorSave.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
colorSave.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
colorPicker.leadingAnchor.constraint(equalTo: leadingAnchor),
colorPicker.topAnchor.constraint(equalTo: bottomAnchor, constant: -256),
colorPicker.trailingAnchor.constraint(equalTo: trailingAnchor),
colorPicker.bottomAnchor.constraint(equalTo: colorSave.topAnchor, constant: -16)
])
}
private func hideUI() {
colorPicker.isHidden = true
colorSave.isHidden = true
}
}
extension ColorPickerView: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return customColor.allValues.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
print(customColor.allValues[row].rawValue)
return customColor.allValues[row].rawValue
}
}
字符串UIPickerView
用于从枚举customColor
中选择颜色。然后可以使用colorSave
按钮隐藏所有元素。
然而,一旦我放置了ColorPickerView
类的示例,它就正确地显示了,但没有滚动。我做错了什么?它和isUserInteractionEnabled
有关系吗?
1条答案
按热度按时间xt0899hw1#
您的自定义视图没有高度。我建议您完全重做您的约束,使其更容易遵循。假设您希望按钮位于选择器视图下方,请执行以下操作:
字符串
这些约束假设UIPickerView有一个固有的高度。我认为它有,但我可能搞错了。如果没有,那么根据需要向
colorPicker
添加一个高度约束。目前,它将选择器的顶部从视图的顶部放置16点,按钮从视图的底部放置16点。它将选择器和按钮之间的间隙设置为20点。它将按钮高度设置为50点。根据需要调整这些。
在设置约束时,考虑自上而下布局和/或左右布局要简单得多。您的代码使所有设置都基于视图的底部。您从未将视图的顶部锚设置为任何内容,因此主视图没有高度。这就是为什么您的选择器和按钮不起作用。它们被零高度父视图剪裁。