我正在使用Xcode 8和swift 3
我创建了一个新项目,当我创建它时选择新的“选项卡式应用程序”。它提供了两个嵌入在一个标签栏控制器中的UIViewControllers。我试图在视图控制器之间传递两个变量。
问题是从不调用segue函数的准备。我在其中添加了一个永不打印的打印声明。我在两个视图控制器中添加了prepare函数,并且可以来回切换而不打印。
一些代码:
import UIKit
import MapKit
import CoreLocation
class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{
@IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager?
var currentLocation:CLLocation?
var destPin: MapPin?
var isTracking: Bool? = false
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.startUpdatingLocation()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.requestAlwaysAuthorization()
updateTracking()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.currentLocation = locations[0]
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getMapView()-> MKMapView{
return mapView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
if(self.isTracking!){
print("Istracking bool is true")
}
else{
print("Istracking bool is false")
}
updateTracking()
locationManager?.stopUpdatingLocation()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("Preparing")
let barViewControllers = segue.destination as! UITabBarController
let destinationViewController = barViewControllers.viewControllers![1] as! FirstViewController
destinationViewController.destPin = self.destPin
destinationViewController.isTracking = self.isTracking
}
}
准备功能的内容也可能是错误的,但即使被调用它也几乎不重要。另一个视图控制器也嵌入在选项卡栏控制器中,并且还具有不执行的准备功能。
如果您愿意,请参阅此github repo
答案 0 :(得分:1)
很容易做到:
结果:
例如,FirstViewController
中嵌入了SecondViewController
和tabViewController
:
在firstViewController.swift
:
import UIKit
class FirstViewController: UIViewController {
var vc1_variable:String = "first vc's variable."
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在secondViewController.swift
:
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let first_vc:FirstViewController = self.tabBarController?.viewControllers![0] as! FirstViewController
print("\(first_vc.vc1_variable)")
}
}