Ich bin mit einem Tutorial gefolgt, aber ein Problem mit einigen Tasten in einer for-Schleife initialisiert.UIButton's in Schleifen, Ereignis nur feuern auf erstes Element
Ich verwende ein Ereignis für jede der Schaltflächen. Aber nur das erste Knopf-Ereignis wird ausgelöst?
Entweder ist das Tutorial falsch oder mir fehlt etwas.
// 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
}
}
Ich sehe, dass Sie die Frames nicht auf diese Schaltflächen setzen!. Wie sehen sie in UI aus? Muss man sich überlappen? – Shripada
Entschuldigung, ich habe die layoutSubviews() hinzugefügt (sollte diese in der ursprünglichen Frage enthalten) ... Die Schaltflächen werden nebeneinander nicht übereinander gerendert –
Wahrscheinlich ist Ihre Superansicht nicht so skaliert, dass sie alle Schaltflächen enthält . Sieht so aus, als ob alle Tasten außer der ersten außerhalb der Grenzen von superview sind. Kannst du überprüfen? – Shripada