我在视图控制器中有很多关于另一个的视图,我试图模拟一个标签栏。用户可以点击菜单上的任何按钮,并且将根据点击的按钮呈现视图。所有其他观点都将隐藏。
我已经编写了以下代码,这些代码没有正确显示视图(有时它们会显示,有时则不显示)。
presentViewWithName(.home) // this will present the view at the very bottom of the hierarchy
enum Views {
case home
case sketchpad
case help
case settings
}
func presentViewWithName(name: Views) {
self.turnAlphaOnToEveryMenuButton()
switch name {
case .home:
self.hideAllViews()
self.menuView.buttonHome.dimmerAlpha()
case .sketchpad:
self.sketchpadView.animateToggleAlpha()
self.menuView.buttonSketchpad.dimmerAlpha()
case .help:
self.helpView.animateToggleAlpha()
self.menuView.buttonHelp.dimmerAlpha()
case .settings:
self.settingsView.animateToggleAlpha()
self.menuView.buttonSettings.dimmerAlpha()
}
}
func turnAlphaOnToEveryMenuButton() {
self.menuView.buttonHome.alpha = 1
self.menuView.buttonSketchpad.alpha = 1
self.menuView.buttonHelp.alpha = 1
self.menuView.buttonSettings.alpha = 1
}
func hideAllViews() {
self.settingsView.alpha = 0
self.sketchpadView.alpha = 0
self.helpView.alpha = 0
}
extension UIView {
func animateToggleAlpha() {
UIView.animateWithDuration(0.25) {
self.alpha = self.alpha == 1 ? 0 : 1
}
}
func dimmerAlpha() {
UIView.animateWithDuration(0.25) {
self.alpha = self.alpha == 1 ? 0.4 : 1
}
}
}
我基本上改变了视图的alpha。假设您要呈现主视图。这是层次结构最底层的视图。我只是隐藏了所有的观点。假设我想在层次结构的最顶部显示视图,即设置视图。我隐藏了所有视图,然后显示设置视图。
我该如何解决这个/更好的做法?
答案 0 :(得分:2)
应该有4个视图回家,草图,帮助和设置。您的所有视图都应具有相同的超级视图。它应分别连接到相同的插座menuViews作为home,sketchpad,help和setting,
@IBOutlet weak var menuViews: [UIView]!
这是你的枚举,
enum Views {
case home
case sketchpad
case help
case settings
}
添加功能以显示该视图,
func presentViewWithName(name: Views) {
UIView.animateWithDuration(0.25) {
for (index, view) in menuViews.enumerate() {
let alpha = (name == (Views(rawValue: index)!)) ? 1.0 : 0.0
view.alpha = alpha
}
}
}