我已经使用 Xcode 进行编码大约两年了,并且遇到了有关在自定义滚动视图中以编程方式初始化的一系列 UIButton 的问题。无论出于何种原因,当点击时,它们的目标函数
@objc func buttonPressed(_ sender: UITapGestureRecognizer)
不会打印语句“按钮按下!”。我以前从未遇到过这个问题,我希望有人能给我指出正确的方向。我已经包含了所有相关的代码,但如果这还不够,我很乐意发布整个类的代码。
{
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!")
}
按钮不会“触发其目标功能”,因为您没有点击按钮,即使您可能认为是这样。
您无法与“超出其超级视图(或该视图的超级视图,以及链上游)边界”的 UI 元素进行交互。 将此行添加到您的代码中:
scrollContent.clipsToBounds = true
并运行应用程序。现在,您甚至不会
看到任何按钮。 您必须为
scrollContent
提供包含按钮的宽度和高度。
您可以让按钮与此行一起使用:// give scrollContent a width and height that fits the buttons
scrollContent.frame.size = .init(width: contentWidth, height: contentHeight)
快速提示:在开发过程中,为所有 UI 元素提供对比背景颜色,以便您可以轻松看到框架。
scrollContent.backgroundColor = .yellow