上面有一些类似的问题,但它们在OBJ-C中,并且没有专门回答我的问题。
我正在构建一个带有卡片上按钮的类似火种的约会应用程序,该应用程序允许当前用户查看显示卡上用户的更多信息。我已经以编程方式编写了此按钮(MoreInfobutton(,并在卡(Uiview(上显示它没有问题。但是,当我单击按钮时,它不起作用。我尝试了类似的和iSuserInteractionEnabled,但两项都没有起作用。这是我的代码:
import UIKit
import SDWebImage
class CardView: UIView {
var imageView = UIImageView(image: #imageLiteral(resourceName: "lady5c"))
var informationLabel = UILabel()
var images: [String]?
var userId: String?
var stackView: UIStackView?
let moreInfoButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "info_icon").withRenderingMode(.alwaysOriginal), for: .normal)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 15
clipsToBounds = true
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
imageView.fillSuperview()
addSubview(informationLabel)
informationLabel.numberOfLines = 0
informationLabel.anchor(top: nil, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 16, bottom: 16, right: 16))
informationLabel.text = ""
informationLabel.textColor = .white
informationLabel.layer.zPosition = 1
addSubview(moreInfoButton)
moreInfoButton.anchor(top: nil, leading: nil, bottom: bottomAnchor, trailing: trailingAnchor, padding: .init(top: 0, left: 0, bottom: 20, right: 20), size: .init(width: 50, height: 50))
moreInfoButton.layer.zPosition = 1
moreInfoButton.isUserInteractionEnabled = true
// let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
// addGestureRecognizer(panGesture)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
如果以编程方式添加一个按钮,我认为您应该使用addArget而不是使用整个Uiview手势。这使按钮具有功能性,而无需与视图手势有任何关系。
lazy var button: UIButton = {
let temp = UIButton(type: .system)
temp.isUserInteractionEnabled = true
temp.addTarget(self, action: someFunction, for: UIControl.Event.touchUpInside)
return temp
}()
我认为uitapgesturerecognizer与按钮点击事件发生冲突。您可以尝试使用Override TouchEsbegan事件而不是Tap手势。
禁用手势的 cancelsTouchesInView
属性。默认情况下,我认为它设置为true
。这意味着手势会消耗触摸事件,并且不会传递到按钮
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapGesture.cancelsTouchesInView = false
addGestureRecognizer(tapGesture)
更新:由于按钮位于可敲击视图的顶部,请确保按钮显示在Tappable视图的前面。如果您使用的是故事板,则该按钮应列在可敲击的视图下方。
另外,在您的触摸began方法中,请确保您不响应按钮内的触摸:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if touch?.view != button && touch?.view == tappableView {
// Next picture
}
}
如果仍然不起作用,请尝试此实现Touchesbegan:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if touch?.view == button {
// performSegue or call button's target function
} else if touch?.view == tappableView {
// Next picture
}
}
您缺少按钮的目标:
moreInfoButton.addTarget(self, action: #selector(buttonTapped(_:)), forControlEvents: .TouchUpInside)
和一个函数来处理水龙头:
@objc func buttonTapped(sender: UIButton!) {
// action
}