I’ve been coding with Xcode for about two years now and I’ve run into an issue regarding a series of UIButtons programmatically initialized in my custom scroll view. For whatever reason, when tapped, their target function @objc func buttonPressed(_ sender: UITapGestureRecognizer)
isn’t printing the statement “Button pressed!”. I’ve never run into this issue before and I was hoping somebody could point me in the right direction. I’ve included all the relevant code, although if this isn’t enough I’d be happy to post the entire class’s code.
{
scrollView.frame = CGRect(x: -10, y: bottomView.layer.position.y - 340, width: view.frame.width + 20, height: 200)
scrollView.backgroundColor = UIColor.black.withAlphaComponent(0.2)
scrollView.layer.zPosition = 350
scrollView.layer.borderColor = UIColor.systemGreen.cgColor
scrollView.layer.borderWidth = 0.3
scrollView.isUserInteractionEnabled = true
let scrollContent = UIView()
scrollContent.isUserInteractionEnabled = true
scrollView.isUserInteractionEnabled = true
let buttonHeight: CGFloat = 70
let buttonSpacing: CGFloat = 15
let numberOfButtonsPerRow = 6
let numberOfRows = 2
let padding: CGFloat = 20
for row in 0..<numberOfRows {
for col in 0..<numberOfButtonsPerRow {
let button = UIButton()
button.frame = CGRect(x: padding + CGFloat(col) * (buttonHeight + buttonSpacing),
y: padding + CGFloat(row) * (buttonHeight + buttonSpacing),
width: buttonHeight,
height: buttonHeight)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .black
button.layer.zPosition = 500
button.isUserInteractionEnabled = true
button.layer.borderColor = UIColor.systemGreen.cgColor
button.layer.borderWidth = 0.75
button.layer.cornerRadius = 10
button.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonPressed(_:)))
button.addGestureRecognizer(tapGesture)
let imageName = buttonImages[row * numberOfButtonsPerRow + col]
button.setImage(UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal), for: .normal)
scrollContent.addSubview(button)
scrollContent.isUserInteractionEnabled = true
}
}
let contentWidth = padding + CGFloat(numberOfButtonsPerRow) * (buttonHeight + buttonSpacing)
let contentHeight = padding + CGFloat(numberOfRows) * (buttonHeight + buttonSpacing)
scrollView.contentSize = CGSize(width: contentWidth, height: contentHeight)
scrollView.addSubview(scrollContent)
view.addSubview(scrollView)
}
@objc func buttonPressed(_ sender: UITapGestureRecognizer) {
print("Button pressed!")
}