我不确定究竟是什么不适合你,我已经实施了一个简单的测试项目,并且我在不释放第一个按钮的情况下按下下一个按钮。这是我写的代码
override func viewDidLoad() {
super.viewDidLoad()
let stackView = UIStackView(frame: CGRect(origin: CGPoint(x: 40.0, y: 40.0), size: CGSize(width: 300, height: 45)))
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 10
let button1 = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 45, height: 45)))
let button2 = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 45, height: 45)))
let button3 = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 45, height: 45)))
[button1, button2, button3].forEach { button in
button.backgroundColor = .blue
stackView.addArrangedSubview(button)
button.addTarget(self, action: #selector(touchDownAction), for: .touchDown)
}
view.addSubview(stackView)
}
@objc func touchDownAction() {
print("touched button")
}
此代码在运行 ios 11.4 的 iphone 上进行了测试。你能提供一些额外的信息吗?
编辑:我已经更新了解决方案,以便在将手指从一个按钮拖动到下一个按钮时它可以工作,抱歉我的误解。希望这对你有用。另外请记住,现在您将遇到另一个问题,当您的手指在按钮内时,您的触摸操作将被连续调用。
var button1: UIButton!
var button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let stackView = UIStackView(frame: CGRect(origin: CGPoint(x: 40.0, y: 40.0), size: CGSize(width: 300, height: 45)))
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 10
button1 = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 45, height: 45)))
button2 = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 45, height: 45)))
[button1, button2].forEach { button in
button!.backgroundColor = .blue
stackView.addArrangedSubview(button!)
}
view.addSubview(stackView)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touchLocation = touches.first!.location(in: view)
let button1FrameInMainView = button1.convert(button1.bounds, to: view)
let button2FrameInMainView = button2.convert(button2.bounds, to: view)
if button1FrameInMainView.contains(touchLocation) {
print("touch inside button 1")
}
if button2FrameInMainView.contains(touchLocation) {
print("touch inside button 2")
}
}