私はチュートリアルに従っていますが、forループで初期化されたいくつかのボタンに問題があります。UIButtonのループ、最初の要素のイベントのみの起動
各ボタンにイベントを適用しています。しかし、最初のボタンイベントだけが起動されていますか?
チュートリアルが間違っているか、何か不足しています。
// 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
}
}
私はあなたがこれらのボタンにフレームを設定していないことがわかります! UIでどのように見えるのですか?互いに重なり合っている必要がありますか? – Shripada
申し訳ありませんが、私はlayoutSubviews()を追加しました(元の質問にこれを含めてください)...ボタンは互いに隣り合って表示されません –
スーパービューのサイズが変更されていない可能性があります。すべてのボタンのように見えるが、最初のものはスーパービューの境界の外にある。確認できますか? – Shripada