gpt4 book ai didi

ios - UIButton 处于循环中,事件仅在第一个元素上触发

转载 作者:行者123 更新时间:2023-11-30 13:30:21 25 4
gpt4 key购买 nike

我正在按照教程进行操作,但在 for 循环中初始化的一些按钮出现问题。

我正在向每个按钮应用一个事件。但只有第一个按钮事件被触发?

要么教程是错误的,要么是我遗漏了一些东西。

// MARK: Properties
var rating = 0 {
didSet {
setNeedsLayout()
}
}

var ratingButtons = [UIButton]()
var spacing = 5
var stars = 5

// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

let emptyStarImage = UIImage(named: "emptyStar")
let filledStarImage = UIImage(named: "filledStar")

for _ in 0..<stars {
let button = UIButton()

button.setImage(emptyStarImage, forState: .Normal)
button.setImage(filledStarImage, forState: .Selected)
button.setImage(filledStarImage, forState: [.Highlighted, .Selected])

button.adjustsImageWhenHighlighted = false

button.addTarget(self, action: "ratingButtonTapped:", forControlEvents: .TouchDown)

ratingButtons += [button]

addSubview(button)
}
}

override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)


// Offset each button's origin by the length of the button plus some spacing.
for (index, button) in ratingButtons.enumerate() {
print(button)
buttonFrame.origin.x = CGFloat(index * (buttonSize + 5))
button.frame = buttonFrame
}

updateButtonSelectionStates()
}

// MARK: Button Action
func ratingButtonTapped(button: UIButton) {

print('I have been clicked') // Can only see on the first button click
rating = ratingButtons.indexOf(button)! + 1
updateButtonSelectionStates()
}

func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerate() {
// If the index of a button is less than the rating, that button shouldn't be selected.
button.selected = index < rating
}
}

最佳答案

事实证明,我对 View Controller 有一个限制,似乎弄乱了“ View 端口”可访问宽度/删除了它,一切都很好

关于ios - UIButton 处于循环中,事件仅在第一个元素上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com