Last active
June 25, 2019 13:08
-
-
Save moaible/2797b8ab069d8d93977771e61870c003 to your computer and use it in GitHub Desktop.
tap tab to change element view controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ButtonViewController: UIViewController { | |
var tapAction: (() -> Void)? | |
private lazy var button: UIButton = { | |
let v = UIButton.init(frame: .init(x: 0, y: 0, width: 60, height: 60)) | |
v.backgroundColor = .orange | |
v.addTarget(self, action: #selector(didTapAction), for: .touchUpInside) | |
return v | |
}() | |
@objc | |
func didTapAction() { | |
tapAction?() | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.addSubview(button) | |
} | |
override func viewDidLayoutSubviews() { | |
super.viewDidLayoutSubviews() | |
button.frame = .init(x: (view.bounds.width - button.frame.width) * 0.5, | |
y: (view.bounds.height - button.frame.height) * 0.5, | |
width: button.frame.width, | |
height: button.frame.height) | |
} | |
} | |
class AViewController: ButtonViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .red | |
} | |
} | |
class B1ViewController: ButtonViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .blue | |
} | |
} | |
class B2ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .green | |
} | |
} | |
class TabController: UITabBarController { | |
let tabA = (item: UITabBarItem(title: "A", image: nil, tag: 0), index: 0) | |
let tabB = (item: UITabBarItem(title: "B", image: nil, tag: 1), index: 1) | |
let aVC = AViewController() | |
let b1VC = B1ViewController() | |
let b2VC = B2ViewController() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
aVC.tabBarItem = tabA.item | |
b1VC.tabBarItem = tabB.item | |
b2VC.tabBarItem = tabB.item | |
setViewControllers([aVC, b1VC], animated: false) | |
aVC.tapAction = { [weak self] in | |
if let idx = self?.tabB.index { | |
self?.selectedIndex = idx | |
} | |
} | |
b1VC.tapAction = { [weak self] in | |
guard let strongSelf = self else { | |
return | |
} | |
strongSelf.setViewControllers([strongSelf.aVC, strongSelf.b2VC], animated: false) | |
} | |
} | |
override func viewWillAppear(_ animated: Bool) { | |
super.viewWillAppear(animated) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment