我正在创建一个带按钮的可滚动菜单。使用按钮标签创建菜单,但是当我单击按钮时,不执行操作。我使用以下代码:
for i in 0...4 {
var aButton = UIButton(type: .custom)
aButton.setImage(UIImage(named: "Hello"), for: .normal)
aButton.frame = CGRect(x: xCoord, y: yCoord, width: buttonWidth, height: buttonHeight)
aButton.tintColor = UIColor.white
aButton.tag = i
aButton.addTarget(self, action: #selector(scrollButAction(sender:)), for: .touchUpInside)
var aLabel = UILabel(frame: CGRect(x: xCoord,y: 40, width: buttonWidth, height: 24))
aLabel.text = labArr[i]
aLabel.textColor = UIColor.white
aLabel.adjustsFontSizeToFitWidth = true
aLabel.font = UIFont.init(name: "HelveticaNeue-Light", size: 14)
scrollView?.addSubview(aButton)
scrollView?.addSubview(aLabel)
xCoord += buttonWidth + buffer
}
我的scrollButAction函数是:
func scrollButAction(sender: UIButton) {
switch sender.tag {
case 0:
print("Hello #0")
case 1:
print("Hello #1")
case 2:
print("Hello #2")
case 3:
print("Hello #3")
case 4:
print("Hello #4")
default:
print("default")
}
}