I am using Xcode 6
with swift
.
I am trying to pass an image / UIImage
from my UITabBarController
to one of the subviews (tabs). The Image itself is being passed to the UITabBarController
using the loadImage function (which is in return called by another UIViewController during prepareForSegue
).
//this is the tab bar controller
class DesignerTabBarController : UITabBarController{
var pickedImage : UIImage = UIImage() //empty image
var VC1: DesignerTabController = DesignerTabController.alloc()
func loadImage(passedImage: UIImage){
pickedImage = passedImage
println(pickedImage) // image is accessible from here
}
override func viewDidLoad() {
super.viewDidLoad()
println(pickedImage) //image is accessible from here
VC1.pickedImageView.image = pickedImage // this line gives "unexpectedly found nil when unwrapping optional"
}
}
//this is the `UIViewcontroller` I want display the image (inside pickedImageView)
class DesignerTabController : UIViewController{
@IBOutlet weak var pickedImageView: UIImageView!
}
I realize that my way of passing the image from the UITabBarController
to the sub-view will not work, even though when there are no syntax errors displayed within Xcode (it suggested pickedImageView when I started typing so I think I am really close to the solution).
If it's not possible passing data from my UITabBarController
to the (first) subview, how can I pass data directly to the first subview? As I explained above, I am passing the image from another view using prepareForSegue. Does prepareForSegue directly to the first view work in my case?
Thank you very much for any suggestions, I'll try them and get back with my findings.
Your tab bar controller has viewControllers
property. Just iterate through it check which controller is kind of class you need.
func passImage(passedImage: UIImage)
{
if viewControllers!.isEmpty{
return
}
for index in 0...viewControllers!.count{
if let controller = viewControllers[index] as? DesignerTabController
controller.pickedImageView.image = passedImage
}
}
solved by using viewDidLayoutSubviews() instead of viewDidLoad()
see below code for my working solution:
class DesignerTabController : UIViewController{
@IBOutlet weak var pickedImageView: UIImageView!
@IBOutlet weak var labelTest: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
class DesignerTabBarController : UITabBarController{
var pickedImage : UIImage = UIImage()
func loadImage(passedImage: UIImage){
pickedImage = passedImage
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
if let controller = viewControllers![0] as? DesignerTabController{
controller.pickedImageView.image = pickedImage
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.