我一直在使用Food Tracker应用程序教程作为学习Swift的项目。我知道这里充满了bug,但我一直在研究正确格式化代码的方法。我进入了星级评分部分,添加了红色按钮,将其分成5个按钮,然后添加了星星。星星出现了一点,但现在根本没有出现在我的模拟器中。我已经清理了我的代码,断开连接并添加了图像和图像代码,断开连接并添加了我的IBOutlets等等。他们仍然没有显示所以我认为我的代码中必须有一些东西,因为我是新手。任何帮助将非常感激。
import UIKit
class RatingControl: UIView {
// 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 filledStar = UIImage(named: "filledStar")
let emptyStar = UIImage(named: "emptyStar")
for _ in 0..<5 {
let button = UIButton()
button.setImage(emptyStar, for: UIControlState())
button.setImage(filledStar, for: .selected)
button.setImage(filledStar, for: [.highlighted, .selected])
button.adjustsImageWhenHighlighted = false
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .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 spacing.
for (index, button) in ratingButtons.enumerated() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
override var intrinsicContentSize : CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + spacing) * stars
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Action
func ratingButtonTapped(_ button: UIButton) {
rating = ratingButtons.index(of: button)! + 1
updateButtonSelectionStates()
}
func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerated() {
// If the index of a button is less than the rating, that button should be selected.
button.isSelected = index < rating
}
}
}
答案 0 :(得分:0)
在你的init?()方法中,你错过了向ratingButtons数组添加按钮的结果,因此在枚举和访问数组时没有任何东西被调高,并且它是空的
请添加以下内容
addSubview(button)
之后
'$valid_attempts'
希望按钮会开始显示。