我正在将UIStepper添加到水平UIStackView中,水平UIStackView本身在垂直UIStackView上。问题是,无论我做什么,UIStepper都不会注册任何事件。
我的代码如下
init(variableIndex: Int, variableName: String, withParentView parent: UIView, currentValue: String, readOnly: Bool) {
// Instantiate the properties
valueTextField = UITextField()
valueStepper = UIStepper()
numberOfDecimals = currentValue.components(separatedBy: ".").count > 1 ? currentValue.components(separatedBy: ".")[1].count : 1
numericValue = Double(currentValue)!
super.init(variableIndex: variableIndex, variableName: variableName, withParentView: parent)
// Horizontal Stack View
let horizontalStackView = UIStackView()
horizontalStackView.axis = .horizontal
horizontalStackView.alignment = .fill
horizontalStackView.spacing = 15
horizontalStackView.distribution = .fill
horizontalStackView.translatesAutoresizingMaskIntoConstraints = false
horizontalStackView.isUserInteractionEnabled = true
// Text Field
valueTextField.text = stringValue
valueTextField.textAlignment = .right
valueTextField.layer.borderWidth = 1.0
valueTextField.layer.cornerRadius = 6.0
valueTextField.layer.borderColor = UIColor.darkGray.cgColor
#warning ("TODO: Enable interaction, change keyboard to numeric and add done button to keyboard")
valueTextField.isUserInteractionEnabled = false
valueTextField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: ConfigFile.rightPadding, height: Int(valueTextField.frame.size.height)))
valueTextField.rightViewMode = .always
// Stepper
valueStepper.value = numericValue
valueStepper.stepValue = 0.1
valueStepper.addTarget(self, action: #selector(self.stepperValueChanged(sender:)), for: .touchUpInside)
valueStepper.addTarget(self, action: #selector(self.test(sender:)), for: .allEditingEvents)
valueStepper.isEnabled = !readOnly
// Create the constraints
constraints.append(NSLayoutConstraint(item: horizontalStackView, attribute: .width, relatedBy: .equal, toItem: stackView, attribute: .width, multiplier: 1.0, constant: 0.0))
horizontalStackView.addArrangedSubview(valueTextField)
horizontalStackView.addArrangedSubview(valueStepper)
stackView.addArrangedSubview(horizontalStackView)
}
@objc private func stepperValueChanged(sender: UIStepper) {
numericValue = valueStepper.value
let userInfo = [
"VariableIndex": String(self.variableIndex),
"NewValue": self.stringValue
]
NotificationCenter.default.post(name: .numericVariableChanged, object: nil, userInfo: userInfo)
}
@objc private func test(sender: UIStepper) {
print("Hi")
}
如您所见,我将事件添加到行中
valueStepper.addTarget(self, action: #selector(self.stepperValueChanged(sender:)), for: .touchUpInside)
valueStepper.addTarget(self, action: #selector(self.test(sender:)), for: .allEditingEvents)
我还尝试在第二行使用.allTouchEvents
参数,但这没用。
UIStepper上方的所有视图的isUserInteractionEnabled
属性均设置为true
在执行过程中,按下UIStepper会得到反馈(它会暂时变色)。
答案 0 :(得分:0)
将.valueChanged
事件与UIStepper
而非.touchUpInside
或.allEditingEvents
一起使用。
答案 1 :(得分:0)
我遇到的问题与here
中描述的问题相同问题是我没有保存对正在生成的对象的任何引用,因此该对象被立即取消了初始化。我通过在保存它的ViewController中保留对它的引用来解决此问题。