ios - 我怎样才能 swift 改变一个屏幕从另一个屏幕的颜色?

标签 ios swift

我有“屏幕 A”和“屏幕 B”,我在“屏幕 A”上有按钮,使用它我可以导航到“屏幕 B”,

在“屏幕 B”上,我有两个按钮“红色按钮”和“绿色按钮”,我想通过按下“屏幕 B”上的按钮来更改“屏幕 A”的颜色

我想用委托(delegate)来做到这一点

即使是 Objective-C 中的解决方案也很有帮助

最佳答案

您可以通过以下方式进行:

protocol ViewControllerBDelegate: class {
   func changeColor(color : UIColor)
}

class ViewControllerB: UIViewController {

   weak var delegate : ViewControllerBDelegate?   

   @IBAction func changeColorInViewController(sender: UIButton) {
       // send the message to change the color in A regarding the color
       sender.tag == 0 ? delegate?.changeColor(UIColor.redColor()) : 
                         delegate?.changeColor(UIColor.greenColor())
   }
}

上面的 ViewControllerViewControllerB,您要在其中更改 ViewControllerA 的颜色。

然后你可以用下面的方式实现ViewControllerA:

class ViewControllerA: UIViewController , ViewControllerBDelegate {

    var viewControllerB : ViewControllerB! 

    // In this method you receive the notification when the button in B is tapped
    func changeColor(color: UIColor) {
       self.view.backgroundColor = color
    } 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {        
       var dest = segue.destinationViewController as! ViewControllerB  

       self.viewControllerB = dest  // instantiate the reference
       self.viewControllerB.delegate = self  // set the delegate for B
    }
}

两件重要的事情:

  1. 我在 prepareForSegue 中设置了对 ViewControllerB 的引用,因为你有一个按钮可以打开 ViewControllerB,但是你手动显示它你可以随心所欲地改变它。
  2. 我只为 ViewControllerB 中的两个按钮实现了一个 action,并为每个按钮分配了一个 tag(您可以在Interface Builder 或代码中)来识别它并发送与按下的按钮相关的颜色,但如果需要,您可以单独执行。

希望对你有帮助

关于ios - 我怎样才能 swift 改变一个屏幕从另一个屏幕的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29414727/

相关文章:

ios - 无法将数组传递到 performSegueWithIdentifier

ios - UITabBar 显示更多图标而不是 "More"选项

ios - 从 url 中提取的图像未出现在 UIImageView 上

iphone/ipad app default.png 图片问题

ios - 使用 TrailingSwipeActionsConfigurationForRowAt 删除单元格时出现一些奇怪的动画错误

ios - 暂停和重置中间动画后进度条动画不正确

ios - 从弹出窗口关闭 UIview IOS 7

ios - 我们如何使用 swift 和 iOS 11+ 进行直线图像转换

ios - 在同一行的页脚中添加两个按钮

swift - 在 Swift 中对继承自 Codable 的类进行子类化导致的崩溃