【发布时间】:2022-01-07 21:04:45
【问题描述】:
我是 swift 和编程的新手。我想学习解决这个问题的最佳方法。
我的 viewController ( storyboard ) 中有一个 UIButton,我在同一个 VC 中的 UIView 中有另一个 UIButton。
第一个按钮将隐藏/取消隐藏视图。
第二个 UIButton,仅在 myView 未隐藏时显示,我希望该按钮也隐藏 myview。所以两个按钮隐藏,一个按钮取消隐藏。
我确定我可以简化这个?
第二个按钮不起作用。我会错过什么? 导入 UIKit
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var outside: UIButton!
@IBOutlet weak var myView: UIView!
@IBOutlet weak var inside: UIView!
var outsideBool: Bool = false
var insideBool: Bool = false
var myIndex: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
myView.isHidden = true
print(insideBool)
print(outsideBool)
}
@IBAction func outsideButtonAction(_ sender: Any) {
outsideBool.toggle()
print(outsideBool)
if outsideBool && myIndex == 1 {
myView.isHidden = false
} else {
if !outsideBool && myIndex == 1 || !outsideBool == !insideBool && myIndex == 1 {
myView.isHidden = true
}
}
}
@IBAction func innerButtonAction(_ sender: Any) {
insideBool.toggle()
}
}
更新了代码创意,但没有按预期工作:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var outside: UIButton!
@IBOutlet weak var myView: UIView!
@IBOutlet weak var inside: UIView!
var outsideBool: Bool = false
var insideBool: Bool = false
var myIndex: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
myView.isHidden = true
print(insideBool)
print(outsideBool)
}
func duh() {
if outsideBool && myIndex == 1 {
myView.isHidden = false
} else if !outsideBool && myIndex == 1 {
myView.isHidden = true
} else if !insideBool && myIndex == 1 {
myView.isHidden = true
}
}
@IBAction func outsideButtonAction(_ sender: Any) {
outsideBool.toggle()
duh()
}
@IBAction func innerButtonAction(_ sender: Any) {
insideBool.toggle()
duh()
}
}
【问题讨论】:
-
您的 outsideButtonAction 函数似乎有点混乱。你为什么不使用 outsideBool ?你永远不会切换它,也永远不会比较它。
-
我刚刚意识到这一点,并将编辑/更新我的问题。谢谢。
-
我明白了!我创建了一个 func 来切换 /caseoutsideBool,我首先比较该值以隐藏或取消隐藏视图,然后在比较之后,在错误的情况下,我比较 innerBool 值并隐藏视图。我觉得仍然很笨拙,但它的工作原理。
标签: swift uiview uibutton boolean operators