我正在尝试向UIView添加点击手势,但手势未被识别。
“iconBadgeView”是一个UIView,其中包含在参数中传递的已定义大小的图像。
Future[Seq[Any]]
有一个委托者附加到同一个类,并且函数实现如下:
lazy var cardioVascularIcon : IconBadgeView! = {
let iconBadgeView = IconBadgeView(frame: CGRect(x: 0, y: 0, width: 95, height: 95), data:["big":"db_history"])
let tapEvent = UITapGestureRecognizer(target: self, action: #selector(loadNewView(sender:)))
tapEvent.numberOfTapsRequired = 1
iconBadgeView.translatesAutoresizingMaskIntoConstraints = false
iconBadgeView.isUserInteractionEnabled = true
iconBadgeView.addGestureRecognizer(tapEvent)
}()
函数loadNewView未被调用。我不确定代码中有什么问题。请有人帮忙。
我将iconBadgeView添加到superview,如下所示:
func loadNewView(sender: UITapGestureRecognizer) {
print("Tapped")
}
答案 0 :(得分:1)
我找到了解决这个问题的方法。我使用了一个按钮而不是一个标签,现在工作正常。以下是我正在使用的代码:
func createButton (buttonWidth : CGFloat?, buttonTitle : String?, buttonFont : UIFont?, imageName : String?, buttonColor : UIColor?) -> UIButton {
let newButton = UIButton(type: . custom)
newButton.showsTouchWhenHighlighted = false
newButton.translatesAutoresizingMaskIntoConstraints = false
newButton.adjustsImageWhenHighlighted = false
if let title = buttonTitle {
newButton.setTitle(title, for: .normal)
}
if let color = buttonColor {
if let _ = newButton.titleLabel {
newButton.setTitleColor(color, for: .normal)
}
}
if let btnWidth = buttonWidth {
newButton.frame = CGRect(x: 0, y: 0, width: btnWidth, height: btnWidth)
newButton.layer.cornerRadius = 0.5 * newButton.bounds.size.width
newButton.clipsToBounds = true
}
if let img = imageName {
newButton.setImage(UIImage(named: img), for: .normal)
}
if let font = buttonFont {
newButton.titleLabel?.font = font
}
return newButton
}
let addDiagButton = self.createButton(buttonWidth: nil, buttonTitle: addButtonTitle, buttonFont: UIFont.regularDisplayOfSize(30), imageName: nil, buttonColor: UIColor(red: 111, green: 160, blue: 186))
addDiagButton.addTarget(self, action: #selector(addDiag(sender:)), for: .touchUpInside)
上面的代码有一个共同的功能,它创建一个按钮并附加触发事件。该代码工作正常。
为了使其行为像标签点击,我在createButton函数中添加了一行。
newButton.adjustsImageWhenHighlighted = false
这将限制单击按钮时的闪光效果。
答案 1 :(得分:0)
你的iconBadgeView消失了,因为它是本地变量。
你必须初始化cardioVascularIcon var。
lazy var cardioVascularIcon : IconBadgeView! = {
cardioVascularIcon.frame = CGRect(x: 0, y: 0, width: 95, height: 95)
//here call function which sets data property
let tapEvent = UITapGestureRecognizer(target: self, action: #selector(loadNewView(sender:)))
tapEvent.numberOfTapsRequired = 1
cardioVascularIcon.translatesAutoresizingMaskIntoConstraints = false
cardioVascularIcon.isUserInteractionEnabled = true
cardioVascularIcon.addGestureRecognizer(tapEvent)
}()