2016-04-15 7 views
0

Я следую инструкциям, но имею проблему с некоторыми кнопками, инициализированными в цикле for.UIButton's in loops, событие только для первого элемента

Я применяю событие к каждой из кнопок. Но только первое событие кнопки запускается?

Либо учебник ошибочен, либо я что-то упускаю.

// 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 
    } 
} 
+1

Я вижу, что вы не устанавливаете кадры на эти кнопки !. Как они выглядят в пользовательском интерфейсе? Должны быть перекрыты друг с другом? – Shripada

+0

К сожалению, я добавил layoutSubviews() (должен был включить это в исходный вопрос) ... Кнопки отображаются рядом друг с другом не друг над другом –

+1

Возможно, ваш супер-просмотр не изменен, чтобы содержать все кнопки , Похоже на все кнопки, но первый из них выходит за рамки супервизора. Вы можете проверить? – Shripada

ответ

0

Оказывается, у меня было ограничение на контроллере представления, что, казалось, портя «вид порта», доступную ширину/удалить его и все хорошо

0

я думаю, что ваша кнопка является слишком большим, вы можете нажать только на один из них. кстати, почему бы не выбрать override init (frame: CGRect) как Инициализация ...