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

时间:2016-04-15 04:05:46

标签: ios swift for-loop uibutton

我跟着一个教程,但是在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
    }
}

2 个答案:

答案 0 :(得分:0)

事实证明我对视图控制器有一个约束,似乎搞乱了'视口“可访问宽度/删除它并且一切都很好

答案 1 :(得分:0)

我认为你的按钮太大,你只能点击其中一个按钮。顺便说一下,为什么不选择覆盖init(frame:CGRect)作为Initialization ...