我正在研究Swift 3.2中Apple的Food Tracker教程,无法正确显示评级的背景。到目前为止一切都很好;没有警告或错误。评级的背景(红色方块)嵌入在水平视图堆栈中。五个红色正方形水平显示,这是正确的,但也有四个红色正方形垂直显示,这是不正确的。我已经三次检查代码,所有看起来都没问题。我也搜索过Stack Overflow,但没有发现任何帮助。我已经包含了RatingControl.swift文件的代码供参考。 (我无法发布图像b / c我没有足够的信誉点。)问题可能与约束有关吗?任何帮助,将不胜感激。 [评级按钮] [1]
//
// RatingControl.swift
// FoodTracker
//
// Created by Jane Appleseed on 10/17/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
import UIKit
@IBDesignable class ratingControl: UIStackView {
//MARK: Properties
private var ratingButtons = [UIButton]()
var rating = 0
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder){
super.init(coder: coder)
setupButtons()
}
//MARK: Button Action
func ratingButtonTapped(button: UIButton) {
print("Button pressed ")
}
//MARK: Private Methods
private func setupButtons() {
for _ in 0..<5 {
// Create the button
let button = UIButton()
button.backgroundColor = UIColor.red
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
// Setup the button action
button.addTarget(self, action: #selector(ratingControl.ratingButtonTapped(button:)), for: .touchUpInside)
// Add the button to the stack
addArrangedSubview(button)
// Add the new button to the rating button array
ratingButtons.append(button)
}
}
}
//![ratings buttons][1]
//[1]: https://i.stack.imgur.com/ofa78.jpg