Passing data between views in ONE ViewController in Swift

后端 未结 2 1688
暖寄归人
暖寄归人 2021-01-15 12:50

All of the searches I\'ve done focus on passing data between view controllers. That\'s not really what I\'m trying to do. I have a ViewController that has multiple Views in

2条回答
  •  失恋的感觉
    2021-01-15 13:29

    EDIT: Sorry, when I created this answer I was having ViewControllers in mind. A much easier way would be to create a method in SomeView and talk directly to it.

    Example:

    class MainViewController: UIViewController {
    
        var view1: SomeView!
        var view2: SomeView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Create the views here
            view1 = SomeView()
            view2 = SomeView()
    
            view.addSubview(view1)
            view.addSubview(view2)
        }
    
        @IBAction func someAction(sender: UIButton) {
            view1.changeString("blabla")
        }
    }
    
    class SomeView: UIView {
    
        var someString: String?
    
        func changeString(someText: String) {
            someString = someText
        }
    }
    

    Delegate:

    First you create a protocol:

    protocol NameOfDelegate: class {     // ": class" isn't mandatory, but it is when you want to set the delegate property to weak
        func someFunction()              // this function has to be implemented in your MainViewController so it can access the properties and other methods in there
    }
    

    In your Views you have to add:

    class SomeView: UIView, NameOfDelegate {
    
        // your code
    
        func someFunction() {
    
            // change your slider settings
        }
    }
    

    And the last step, you'll have to add a property of the delegate, so you can "talk" to it. Personally I imagine this property to be a gate of some sort, between the two classes so they can talk to each other.

    class MainViewController: UIViewController {
    
        weak var delegate: NameOfDelegate?
    
        @IBAction func button(sender: UIButton) {
            if delegate != nil {
                let someString = delegate.someFunction()
            }
        }
    }
    

    I used a button here just to show how you could use the delegate. Just replace it with your slider to change the properties of your Views

    EDIT: One thing I forgot to mention is, you'll somehow need to assign SomeView as the delegate. But like I said, I don't know how you're creating the views etc so I can't help you with that.

提交回复
热议问题