UIKit-Pass Data Between View Controllers
这几天都在写播放器… 相关的内容写完再上传吧
本文来源:https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/
Use var controller
假设我们有两个ViewController
名为First和Second
Second里面有一个UILabel
1 | class Second: UIViewController { |
那么从First传递到Second呢
1 | @objc func b() { |
其中道理都懂
Here’s what happens in that piece of code:
- You create a constant called
vc
and assign it an instance ofSecond
. You pass the right XIB name in the initializer to make sure the view controller uses the correct XIB file.- You then assign a string to the property
text
onvc
. This is the actual passing of the data between the view controllers!- Finally, you push the new view controller onto the navigation stack with
pushViewController(_:animated:)
. The change is animated, so when it’s executed you’ll see the new view controller “slide in” from the right of the iPhone screen.
那么从Second
传到First
怎么办呢,我们当然可以再次使用这种方法
That’s all there is to it. But… this approach for passing data isn’t the most ideal. It has a few major drawbacks:
- The
MainViewController
andSecondaryViewController
are now tightly coupled. You want to avoid tight-coupling in software design, mostly because it decreases the modularity of your code. Both classes become too entangled, and rely on each other to function properly, with often leads to spaghetti code.- The above code example creates a retain cycle. The secondary view controller can’t be removed from memory until the main view controller is removed, but the main view controller can’t be removed from memory until the secondary view controller is removed. (A solution would be the
weak
property keyword.)- Two developers can’t easily work separately on
MainViewController
andSecondaryViewController
, because both view controllers need to have an understanding about how the other view controller works. There’s no separation of concerns.
这会导致两个ViewController
的高度耦合,同时也增加了栈
我们可以使用Delegation
来传递数据
Use delegation
我们先创建一个protocol
1 | protocol sendMethod{ |
然后让First, Second遵守senfMethod
1 | var delegate:sendMethod? |
然后转过去就行了
Use closure
这是在First中
1 | var completionHandler:((String) -> Int)? = { text in |
那么在Second中实现
1 | let vc = First() |
就可以在不同的ViewController
中互用方法
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记!