我对Apple的基本Swift教程的sixth chapter有疑问。
问题是只有第一颗星(UIButton)正在工作。我在for循环中创建了所有星星,并为每个UIButton调用addTarget方法一次。所以基本上每个按钮的代码都是一样的。现在一个非常奇怪的行为即将出现,在iPad模拟器上,所有iPhone模拟器上的一切都正常工作不同iPhone 6没有明星的作用,而在所有其他iPhone上只有第一颗星正在工作,在我真正的iPhone 6上也一样。
带有for循环的init方法:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let filledStarImage = UIImage(named: "filledStar")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<starCount {
let button = UIButton()
button.setImage(emptyStarImage, forState: .Normal)
button.setImage(filledStarImage, forState: .Selected)
button.setImage(filledStarImage, forState: [.Highlighted, .Selected])
button.adjustsImageWhenHighlighted = false
ratingButtons += [button]
ratingButtons.last!.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
self.addSubview(button)
}
}
行动方法:
func ratingButtonTapped(button: UIButton){
rating = ratingButtons.indexOf(button)! + 1
updateButtonSelectionState()
}
func updateButtonSelectionState() {
for (index, button) in ratingButtons.enumerate(){
button.selected = index < rating
}
}
布局子视图方法:
override func layoutSubviews() {
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize , height: buttonSize)
for (index, button) in ratingButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionState()
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = buttonSize * starCount + spacing * (starCount - 1)
return CGSize(width: width, height: buttonSize)
}
您对如何使按钮在每台设备上运行有任何建议吗?