所以我的iOS应用程序有以下布局。
我打算做的是在purpleVC中放置一个表格视图来控制绿色视图控制器...顶部的peachVC将在其中包含需要更改的文本。我不知道如何从另一个控制一个视图控制器。这包括在单击GreenVC上的按钮时让紫色滑块进出。我知道有些课程要做,但我也想学习。
测试代表:
MAINVIEW CONTROLER
import UIKit
protocol Purpleprotocol {
func buttonpressed()
}
protocol Greenprotocol {
}
extension UIViewController {
func alert(message: String, title: String = "") {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
class MainViewController: UIViewController,Purpleprotocol,Greenprotocol {
weak var infoNav : UINavigationController?
weak var greenVC: GreenVC?
weak var purpleVC: PurpleVC?
weak var peachVC: PeachVC?
func buttonpressed() {
alert(message: "This is message")
print("buttonpressed")
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
greenVC?.greenlabel.text = String(hour) + ":" + String(minutes)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "contentSegue" {
let infoNav = segue.destination as! UINavigationController
}
}
}
PURPLEVIEW CONTROLER
class PurpleVC: UIViewController {
var delegate: Purpleprotocol?
@IBAction func butclick(_ sender: UIButton) {
alert(message: "infunction")
delegate?.buttonpressed()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
由于 [R
答案 0 :(得分:0)
这取决于具体情况,但要看几个例子:
A)您可以通过代理人连接它。您的主视图控制器有3个子视图控制器,它应报告更改。它还应该将自己分配给所有3个子控制器的委托,它将获得所有事件通知。这看起来像
func purpleViewController(sender: PVC, selectedItem: Item) {
self.greenViewController.showItem(item: selectedItem)
self.peachVC.showItem(item: selectedItem)
}
func purpleViewController(sender: PVC, shouldSetMenuClosed closed: Bool) {
self.menuConstraint.constant = closed ? targetWidth : 0.0
}
B)您可能拥有一个控制整个屏幕的数据模型,并且每个子项都有一个委托。该模型将向其代表报告任何更改,以便他们做出相应的反应。主视图控制器在加载时会创建该模型的实例,并将其传递给所有子视图控制器。然后孩子们会直接操纵模型:
在绿色控制器中:
func onTap() {
mode.menuShown = !mode.menuShown
}
模特:
var menuShown: Bool = true {
didSet {
self.menuDelegate.model(self, changedMenuShownStateTo: menuShown)
}
}
在主视图控制器中:
func model(_ sender: Model, changedMenuShownStateTo shown:Bool) {
self.menuConstraint.constant = shown ? 0.0 : targetWidth
}
C)您可以使用通知,其中任何控制器都可以向通知中心发布自定义通知,其他控制器可以观察通知并采取相应行动。
还有许多其他方法,但这些可能最受欢迎。看看它们是否适合你......