【发布时间】:2016-09-18 17:24:39
【问题描述】:
随着 Swift 3.0 和 Xcode 8.0 的发布,我决定看看我最近在 Apple 的 自己的项目之后构建的一个项目指导Start Developing iOS Apps (Swift) - 您可以下载示例项目here。
在转换为当前的 Swift 语法并对项目进行一些小的调整后,代码编译没有错误,应用程序运行完美,除了 RatingControl.swift 中定义的自定义控件不可见。使用 Interface Builder 将视图移出堆栈视图会使其可见,但一旦添加约束,它就会再次消失。
是bug还是代码需要进一步调整?
为了完整起见:代码是自动转换的,Privacy Photo Library Usage Description 被添加到 Info.plist,强制展开在 saveMeals() 和 loadMeals() 中被移除,额外的向下转换被添加到位于 prepare(for:sender:) 中的 MealViewController.swift .
提前谢谢你。
界面生成器
RatingControl.swift
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 filledStarImage = UIImage(named: "filledStar")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<5 {
let button = UIButton()
button.setImage(emptyStarImage, for: UIControlState())
button.setImage(filledStarImage, for: .selected)
button.setImage(filledStarImage, 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
}
}
}
【问题讨论】:
标签: swift xcode uikit interface-builder