选择另一个选项卡时如何更改文本字段的背景颜色?

How to change background color of text field when selecting another tab?

我有一个带有四个选项卡的选项卡控制器。在其中两个选项卡上,我有具有数据验证功能的文本字段。如果数据验证失败,它将背景颜色更改为红色。但是,当我切换到另一个选项卡并返回到带有数据验证的选项卡时,文本字段仍然具有红色背景。如何在离开带有数据验证的选项卡后更改文本字段的背景颜色?

我试过将它添加到 viewDidLoad()

self.textName.backgroundColor = UIColor.white

我试过了

func tabBarController(_ tabBarController: UITabBarController, 
  didSelect viewController: UIViewController) {
      let tabBarIndex = tabBarController.selectedIndex
      if tabBarIndex == 1 {
        self.textName.backgroundColor = UIColor.white
    }
}

这些方法都不起作用。谢谢!

您可以在 viewWillAppear/viewDidAppear 中尝试,因为 viewDidLoad 在 VC 加载时被调用一次

self.textName.backgroundColor = UIColor.white

为了didSelect,你需要

self.tabBarController?.delegate = self