How can I switch from xib file to viewcontroller? - ios

When the image in the view I created with xib is clicked, I want it to go to the view controller in the storyboard. I tried segue-present and pushviewcontroller() but how can I do it?
Also, the delegate nil in the imageClicked() function is coming.delagate should not be nil
This is xib file:
xib view
import UIKit
protocol BookDetailVideoViewDelegate : class {
func videoOpen(value: Bool)
}
class BookDetailVideoViewController: UIViewController{
weak var delegate : BookDetailVideoViewDelegate?
var book : Book?
var videoUrl = ""
var url: URL?
var index = 0
#IBOutlet weak var bookImageView: UIImageView!
//var book = self.book
#IBOutlet weak var bookImageViewWidthConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
self.extendedLayoutIncludesOpaqueBars = true
} else {
self.edgesForExtendedLayout = []
}
self.navigationController?.navigationBar.isTranslucent = false
//self.bookImageViewWidthConstraint.constant = UIScreen.main.bounds.width * 0.35
self.view.layoutIfNeeded()
if let url = self.url {
self.bookImageView.kf.setImage(with: url)
}
self.bookImageView.layer.cornerRadius = 10
bookImageView.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageClicked))
bookImageView.addGestureRecognizer(gestureRecognizer)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
self.url = nil
}
#objc func imageClicked(){
print(delegate as Any)
self.delegate?.videoOpen(value: true)
}
func initializeView(url: URL, index: Int , book: Book) {
self.index = index
self.url = url
self.book = book
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
}
The view controller is like this:
import UIKit
import YoutubePlayer_in_WKWebView
class YoutubeVideoViewController: UIViewController , BookDetailVideoViewDelegate, WKYTPlayerViewDelegate {
let myDelegate : BookDetailVideoViewController = BookDetailVideoViewController()
var boolvalue = true
var book : Book?
#IBOutlet weak var playerView: WKYTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
playerView.delegate = self
myDelegate.delegate = self
let mediakey = book!.mediaKey as String?
playerView.load(withVideoId: mediakey!)
}
func videoOpen(value : Bool) {
guard let ViewC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YoutubeVideoViewController") as? YoutubeVideoViewController else{return}
ViewC.book = book
ViewC.boolvalue = value
self.present(ViewC, animated: true)
}
}

Related

How to fix pass date between 2 ViewControllers

I try to pass imageName string data from ViewController to ImageViewController
which also func sliderImageTapped is sending data to CPImageSlider class
// ViewController.swift
import UIKit
let _AUTO_SCROLL_ENABLED : Bool = false
class ViewController: UIViewController, CPSliderDelegate {
var imagesArray = [String]()
var passDataDelegate: PassImageName?
#IBOutlet weak var slider : CPImageSlider!
#IBOutlet weak var autoSwitch : UISwitch!
#IBOutlet weak var arrowSwitch : UISwitch!
#IBOutlet weak var indicatorSwitch : UISwitch!
#IBOutlet weak var sliderSwitch : UISwitch!
#IBOutlet weak var circularSwitch : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = ["wallpaper1.jpg","wallpaper2.jpg","wallpaper3.jpg","wallpaper4.jpg"]
slider.images = imagesArray
slider.delegate = self
let zoom : CGFloat = 0.8
autoSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
arrowSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
indicatorSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
sliderSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
circularSwitch.transform = CGAffineTransform(scaleX: zoom, y: zoom)
autoSwitch.isOn = slider.autoSrcollEnabled
arrowSwitch.isOn = slider.enableArrowIndicator
indicatorSwitch.isOn = slider.enablePageIndicator
sliderSwitch.isOn = slider.enableSwipe
circularSwitch.isOn = slider.allowCircular
}
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
passDataDelegate?.passData(clickedImageName: imageName)
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
}
// ImageViewController.swift
import UIKit
protocol PassImageName {
func passData(clickedImageName:String)
}
class ImageViewController: UIViewController, PassImageName {
#IBOutlet weak var image: UIImageView!
var imageName:String?
func passData(clickedImageName: String) {
imageName = clickedImageName
}
override func viewDidLoad() {
super.viewDidLoad()
image.image = UIImage(named: imageName ?? "wallpaper1.jpg")
}
#IBAction func dismiss(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
You must initialize passDataDelegate before call the delegate method.
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
passDataDelegate = destinationVC
passDataDelegate?.passData(clickedImageName: imageName)
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
I don't understand the point of your delegate, is there something preventing you to just set the imageName after instantiating the ImageViewController ?
func sliderImageTapped(slider: CPImageSlider, imageName: String, index: Int) {
guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController else {
return
}
destinationVC.imageName = imageName
present(destinationVC, animated: true, completion: nil )
print("\(index)")
}
And then just set your image inside it :
var imageName:String? {
didSet {
image.image = UIImage(named: imageName ?? "wallpaper1.jpg")
}
}

How to change button title every time checkmark selected within custom cell

I have a viewcontroller that has a tableview and a button at the bottom. Within each cell is a radio button as a tapGesture. I would like to updated the button with the number of cells selected. If my gesture is in the custom cell and my button is in my viewcontroller how can I get the two to work together?
Custom cell:
class SearchTalentCell: UITableViewCell {
#IBOutlet weak var userProfileImage: UIImageView!
#IBOutlet weak var talentUserName: UILabel!
#IBOutlet weak var selectedImg: UIImageView!
#IBOutlet weak var inviteSentImg: UIImageView!
var prospectRef: FIRDatabaseReference!
var currentTalent: UserType!
func setTalent(talent: UserType) {
currentTalent = talent
currentTalent.userKey = talent.userKey
}
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: #selector(selectTapped))
tap.numberOfTapsRequired = 1
selectedImg.addGestureRecognizer(tap)
selectedImg.isUserInteractionEnabled = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(user: UserType, img: UIImage? = nil) {
prospectRef = Cast.REF_PRE_PRODUCTION_CASTING_POSITION.child(ProjectDetailVC.currentProject).child(FIRDataCast.prospect.rawValue).child(CastingDetailVC.positionName).child(user.userKey)
setTalent(talent: user)
self.talentUserName.text = "\(user.firstName) \(user.lastName)"
prospectRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let _ = snapshot.value as? NSNull {
self.inviteSentImg.isHidden = true
} else {
self.inviteSentImg.image = UIImage(named: "inviteSent")
self.inviteSentImg.isHidden = false
}
})
if UserType.selectedTalentForSearch.contains(currentTalent.userKey) {
selectedImg.image = UIImage(named: "radioSelected")
} else {
selectedImg.image = UIImage(named: "radioUnselected")
}
//Image Caching
if img != nil {
self.userProfileImage.image = img
} else {
if let imageURL = user.profileImage {
let ref = FIRStorage.storage().reference(forURL: imageURL)
ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, error) in
if error != nil {
print("ZACK: Unable to download image from Firebase Storage")
} else {
print("ZACK: Image downloaded from Firebase Storage")
if let imgData = data {
if let img = UIImage(data: imgData) {
self.userProfileImage.image = img
SearchTalentVC.userProfileImageCache.setObject(img, forKey: imageURL as NSString)
}
}
}
})
}
}
}
#objc func selectTapped(sender: UITapGestureRecognizer) {
if UserType.selectedTalentForSearch.contains(currentTalent.userKey) {
selectedImg.image = UIImage(named: "radioUnselected")
UserType.selectedTalentForSearch = UserType.selectedTalentForSearch.filter{$0 != currentTalent.userKey}
print("Keys: \(UserType.selectedTalentForSearch)")
} else {
selectedImg.image = UIImage(named: "radioSelected")
UserType.selectedTalentForSearch.append(currentTalent.userKey)
print("Keys: \(UserType.selectedTalentForSearch)")
}
}
}
ViewController:
class SearchTalentVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var sendInviteButton: UIButton!
var searchingRole = [Cast]()
var unfilteredTalent = [UserType]()
var filteredTalent = [UserType]()
var selectedTalent = [UserType]()
var matchingTalentUserKeys = [String]()
var isFiltered = false
var selectedCounter = [String]()
var prospectRef: FIRDatabaseReference!
static var userProfileImageCache: NSCache<NSString, UIImage> = NSCache()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search Talent"
searchController.searchBar.barStyle = .black
navigationItem.searchController = searchController
definesPresentationContext = true
searchController.searchBar.scopeButtonTitles = ["All", "Role Specific"]
searchController.searchBar.tintColor = UIColor.white
searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
self.sendInviteButton.setTitle("Send Invite to \(UserType.selectedTalentForSearch.count) Prospects", for: .normal)
getTalentProfiles()
}
Thank you for any help!
I'm not sure why you are using the cell selection inside the cell, as opposed to the tableview delegate function func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)?
If you use didSelectRowAt, you could have an array of selected rows and you can include the selectedRows.count into your button text.
Hope that helps!

Pass data between childViewControllers Swift

I put a container inside my MainViewController. Then added FirstViewController inside that container
let containerView = UIView()
view.addSubview(containerView)
let controller = FirstViewController()
addChildViewController(controller)
containerView.addSubview(controller.view)
controller.didMove(toParentViewController: self)
There are a UITextField and a UIButton inside FirstViewController. There is a label inside SecondViewController and var passedText = "" to update the UILabel text. I just want to set the UILabel text according to the UITextField text from FirstViewController when I press UIButton and it should leads to SecondViewController as well. This is the UIButton action method from FirstViewController. I'm not using Storyboard
#IBAction func btnPressed(_ sender: Any) {
let secondVC = SecondViewController()
addChildViewController(secondVC)
view.addSubview(secondVC.view)
secondVC.view.frame = view.bounds
secondVC.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
secondVC.didMove(toParentViewController: self)
secondVC.passedText = inputTextField.text!
}
This is FirstViewController
class FirstViewController: UIViewController {
#IBOutlet weak var inputTextField: UITextField!
let secondVC = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnPressed(_ sender: Any) {
addChildViewController(secondVC)
view.addSubview(secondVC.view)
secondVC.view.frame = view.bounds
secondVC.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
secondVC.didMove(toParentViewController: self)
secondVC.passedText = inputTextField.text!
}
}
This is SecondViewController
class SecondViewController: UIViewController {
var passedText = ""
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = passedText
}
}
Closure
class ParentViewController: UIViewController {
var embeddedViewController: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
let firstViewController = FirstViewController()
embedViewController(firstViewController)
firstViewController.passDataClosure = { [weak self] text in
let secondViewController = SecondViewController()
self?.embedViewController(secondViewController)
secondViewController.passedText = text
}
}
func embedViewController(_ viewController: UIViewController) {
removeEmbedded()
viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addChildViewController(viewController)
view.addSubview(viewController.view)
viewController.didMove(toParentViewController: self)
embeddedViewController = viewController
}
func removeEmbedded() {
embeddedViewController?.view.removeFromSuperview()
embeddedViewController?.didMove(toParentViewController: nil)
embeddedViewController?.removeFromParentViewController()
}
}
-
class FirstViewController: UIViewController {
var passDataClosure: ((String?) -> Void)?
#IBOutlet weak var inputTextField: UITextField!
#IBAction func btnPressed(_ sender: Any) {
passDataClosure?(inputTextField.text)
}
}
-
class SecondViewController: UIViewController {
var passedText: String? {
didSet {
label.text = passedText
}
}
#IBOutlet weak var label: UILabel!
}
Delegate
class ParentViewController: UIViewController, FirstViewControllerDelegate {
var embeddedViewController: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
let firstViewController = FirstViewController()
embedViewController(firstViewController)
firstViewController.delegate = self
}
func embedViewController(_ viewController: UIViewController) {
removeEmbedded()
viewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addChildViewController(viewController)
view.addSubview(viewController.view)
viewController.didMove(toParentViewController: self)
embeddedViewController = viewController
}
func removeEmbedded() {
embeddedViewController?.view.removeFromSuperview()
embeddedViewController?.didMove(toParentViewController: nil)
embeddedViewController?.removeFromParentViewController()
}
// MARK: FirstViewControllerDelegate
func firstViewController(_ firstViewController: FirstViewController, pass text: String?) {
let secondViewController = SecondViewController()
embedViewController(secondViewController)
secondViewController.passedText = text
}
}
-
class SecondViewController: UIViewController {
var passedText: String? {
didSet {
label.text = passedText
}
}
#IBOutlet weak var label: UILabel!
}
-
protocol FirstViewControllerDelegate: class {
func firstViewController(_ firstViewController: FirstViewController, pass text: String?)
}
class FirstViewController: UIViewController {
weak var delegate: FirstViewControllerDelegate?
#IBOutlet weak var inputTextField: UITextField!
#IBAction func btnPressed(_ sender: Any) {
delegate?.firstViewController(self, pass: inputTextField.text)
}
}
As far as I can see, this should work:
secondVC.label.text = inputTextField.text
You currently have secondVC.label = inputTextField.text which shouldn't even compile.
you can create a singleton class for your scenario. so that you can access all of your important data from anywhere either from your firstViewController or SecondViewController.
class YourDataClass : NSObject{
var textFieldData = String()
var lblSeconddata = String()
struct Static
{
public static var instance: YourDataClass?
}
class var singleton: YourDataClass
{
if Static.instance == nil
{
Static.instance = YourDataClass()
}
return Static.instance!
}
}
now somewhere in your controller
YourDataClass.Singleton.textFieldData = txtFld.Text
YourDataClass.Singleton. lblSeconddata = lblText.Text
in smame way you can get it anywhere

Swift - Delegate through Nav Controller

I'm going to include my full code in this but I will try to give pointers to where the relevant bits are. Basically I am returning to a view controller from an Unwind Segue with some new data. I am using that data successfully in the 'NBARotoHome' VC but I additionally need to pass some of that data through an embedded Nav controller to 'NBARotoTabPager' vc.
I am trying to do this using the 'UpdateChildView' delegate (at the top of the first block of code) and calling its method in 'loadViewData() (in the 'if statement' near the bottom of the first block).
protocol UpdateChildView : class {
func updateView()
func test()
var playerSelected: Player? { get set }
}
class RotoViewRoundCell: UITableViewCell{
#IBOutlet weak var categoryLabel: UILabel!
}
class RotoViewRoundHeader: UITableViewCell{
}
class NBARotoHome: UIViewController{
#IBOutlet weak var posPaidLabel: UILabel!
#IBOutlet weak var progressIndicator: UIProgressView!
#IBOutlet weak var vsLabel: UILabel!
#IBOutlet weak var fantasyFundsAmountLabel: UILabel!
#IBOutlet weak var fantasyFundsLabel: UILabel!
#IBOutlet weak var playerName: UILabel!
#IBOutlet weak var roundIndicator: UILabel!
var selectedPlayer: Player!
var firstNavController: UINavigationController!
weak var updateChildView : UpdateChildView?
override func viewDidLoad() {
super.viewDidLoad()
loadViewData()
firstNavController = self.navigationController
let rightBarButton = UIBarButtonItem(title: "Select", style: UIBarButtonItemStyle.plain, target: self, action: #selector(myRightSideBarButtonItemTapped(_:)))
self.navigationItem.rightBarButtonItem = rightBarButton
self.title = "NBA Roto"
}
func myRightSideBarButtonItemTapped(_ sender:UIBarButtonItem!){
performSegue(withIdentifier: "ShowDraft", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDraft" {
let navVC = segue.destination as? UINavigationController
let nbaDraftList = navVC?.viewControllers.first as! NBADraftList
nbaDraftList.mainNavController = firstNavController
}
if (segue.identifier == "buyNavControllerChild"){
// let navVC = segue.destination as? UINavigationController
// let buyVC = navVC?.viewControllers.first as! NBARotoTabPager
// buyVC.delegate = self
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
#IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
}
func loadViewData(){
if((selectedPlayer) != nil){
roundIndicator.text = "Upcoming: " + selectedPlayer.game_time
playerName.text = selectedPlayer.Name
vsLabel.text = selectedPlayer.visiting + " # " + selectedPlayer.home
fantasyFundsLabel.text = ""
fantasyFundsAmountLabel.text = ""
updateChildView?.test()
// updateChildView?.playerSelected = selectedPlayer
// updateChildView?.updateView()
}else{
roundIndicator.text = "Select a Player"
playerName.text = "No Player Selected"
vsLabel.text = "--"
fantasyFundsLabel.text = "Fantasy Funds"
fantasyFundsAmountLabel.text = "$10,000"
}
}
}
Because I haven't been able to get the delegate to work, I have been playing around with setting its delegate property in the above 'prepare' method -'buyVC.delegate = self' - but I'm getting 'buyVC has no member delegate' so that has been a dead end.
The next bit of code is the NBARotoTabPager vc which is embedded in the navigation controller. For reasons I'm no longer sure about I decided to make it a subclass of NBARotoHome, but its basically a custom tab pager that uses a segmented control to switch between two additional vcs.
The most important step at this point is just getting the 'test' function to work (which just prints 'test'. Its implemented in the below block of code second from the bottom above updateView).
class NBARotoTabPager: NBARotoHome, UpdateChildView{
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var scoreKey: UIBarButtonItem!
#IBOutlet weak var standings: UIBarButtonItem!
var playerSelected: Player?
override func viewDidLoad() {
navigationController?.navigationBar.barTintColor = UIColor(red: 27/255, green: 27/255, blue: 27/255, alpha: 1)
scoreKey.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Helvetica", size: 13.0)!], for: UIControlState.normal)
scoreKey.tintColor = UIColor.blue
standings.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Helvetica", size: 13.0)!], for: UIControlState.normal)
standings.tintColor = UIColor.blue
setupView()
}
private func setupView() {
setupSegmentedControl()
updateView()
}
private func setupSegmentedControl() {
// Configure Segmented Control
segmentedControl.removeAllSegments()
segmentedControl.insertSegment(withTitle: "Live", at: 0, animated: false)
segmentedControl.insertSegment(withTitle: "Avg / +", at: 1, animated: false)
segmentedControl.addTarget(self, action: #selector(selectionDidChange(_:)), for: .valueChanged)
segmentedControl.selectedSegmentIndex = 0
}
func selectionDidChange(_ sender: UISegmentedControl) {
updateView()
}
private lazy var viewLiveTab: NBARotoLive = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "NBARotoLive") as! NBARotoLive
if((self.playerSelected) != nil){
viewController.selectedPlayer = self.playerSelected
}
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
private lazy var viewAvgsTab: NBARotoAvgs = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "NBARotoAvgs") as! NBARotoAvgs
if((self.playerSelected) != nil){
viewController.selectedPlayer = self.playerSelected
}
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
private func add(asChildViewController viewController: UIViewController) {
// Add Child View Controller
addChildViewController(viewController)
// Add Child View as Subview
view.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = view.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParentViewController: self)
}
private func remove(asChildViewController viewController: UIViewController) {
// Notify Child View Controller
viewController.willMove(toParentViewController: nil)
// Remove Child View From Superview
viewController.view.removeFromSuperview()
// Notify Child View Controller
viewController.removeFromParentViewController()
}
internal func test(){
print("test")
}
internal func updateView() {
if segmentedControl.selectedSegmentIndex == 0 {
let position = viewAvgsTab.tableView.contentOffset.y;
viewLiveTab.tableView.contentOffset = CGPoint(x:0, y:position);
remove(asChildViewController: viewAvgsTab)
add(asChildViewController: viewLiveTab)
} else {
let position = viewLiveTab.tableView.contentOffset.y;
viewAvgsTab.tableView.contentOffset = CGPoint(x:0, y:position);
remove(asChildViewController: viewLiveTab)
add(asChildViewController: viewAvgsTab)
}
}
}
I've looked at a lot of examples but I don't understand the whole 'setting the delegate' thing i.e. theSecondViewController.delegate = self. Sometimes I see examples where you don't need to do this. And other times it seems like my VCs don't even have a delegate property. So I'm not sure if that's my specific problem or not but any direction would be greatly appreciated. Thanks
There are three steps to implement a delegate.
create a protocol.. (you've already done this by creating a updateChildView protocol)
you need to implement this protocol in the class you wish to receive and process this data.. (you've not done this step and thats why you cant set buyVC.delegate = self)
you need to add a property in ViewController2 called "delegate" and make it as a type of your protocol in step 1 (you've not done this step and there is no property called "delegate" in vc2 .. that's why you get this error 'buyVC has no member delegate')
Here's a quick example:
Protocol:
protocol UpdateChildView{ //removed :class
func updateView()
func test()
var playerSelected: Player? { get set }
}
Viewcontroller A:
class NBARotoHome: UIViewController, UpdateChildView { //added conformance to the protocol
//add the methods for conforming to protocol and add your implementation
func updateView() {
//add your implementation
}
func test(){
//add your implementation
}
var playerSelected: Player? {
//add your implementation
}
prepare(for: Segue) {
/** code for passing data **/
let navVC = segue.destination as? UINavigationController
let buyVC = navVC?.viewControllers.first as! NBARotoTabPager
buyVC.delegate = self
//sets the delegate in the new viewcontroller
//remember.. delegate is a property in the next vc
// and the property only accepts any viewcontroller that is implements updatechildview protocol
present(vc2)
}
}
viewcontroller2 :
class viewControllerB: UIViewController {
var delegate: UpdateChildView? //add this
viewdidload {
delegate?.test() //call the func in the previous vc
}
}

Pass data to and from Popover in Swift

In my current project i have detail view that shows a specific record from my table view. I have the following labels
#IBOutlet weak var vacationImageView: UIImageView!
#IBOutlet weak var percentSaved: UILabel!
#IBOutlet weak var cost: UILabel!
#IBOutlet weak var saved: UILabel!
#IBOutlet weak var circleProgressView: CircularProgressView!
#IBOutlet weak var daysDepart: UILabel!
I call a popover that I want to send the current text value of saved to my popup, allow the user to edit it and send it back to the view. Here is my popover call.
#IBAction func addPopover(sender: UIView) {
let savingsInformationViewController = storyboard?.instantiateViewControllerWithIdentifier("SavingsAddPopover") as UIViewController
savingsInformationViewController.modalPresentationStyle = .Popover
savingsInformationViewController.preferredContentSize = CGSizeMake(200, 200)
let popoverController = savingsInformationViewController.popoverPresentationController
popoverController?.sourceView = sender
popoverController?.permittedArrowDirections = .Any
popoverController?.delegate = self
presentViewController(savingsInformationViewController, animated: true, completion: nil)
}
I would have thought I could reference the data object from the popover but can't..at least not the way I'm thinking.
class ViewController: UIViewController,SavingViewControllerDelegate,UIPopoverPresentationControllerDelegate{
#IBOutlet var labelText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func buttonPopOverClick(sender: UIButton)
{
let savingsInformationViewController = storyboard?.instantiateViewControllerWithIdentifier("SavingsAddPopoverVC") as SavingViewController
savingsInformationViewController.delegate = self
savingsInformationViewController.strSaveText=labelText.text
savingsInformationViewController.modalPresentationStyle = .Popover
if let popoverController = savingsInformationViewController.popoverPresentationController {
popoverController.sourceView = sender
popoverController.sourceRect = sender.bounds
popoverController.permittedArrowDirections = .Any
popoverController.delegate = self
}
presentViewController(savingsInformationViewController, animated: true, completion: nil)
}
func saveText(strText: NSString) {
labelText.text=strText
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
return .FullScreen
}
func presentationController(controller: UIPresentationController!, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController! {
return UINavigationController(rootViewController: controller.presentedViewController)
}
}
protocol SavingViewControllerDelegate
{
func saveText(var strText : NSString)
}
class SavingViewController: UIViewController {
#IBOutlet var textField: UITextField!
var delegate : SavingViewControllerDelegate?
var strSaveText : NSString!
override func viewDidLoad() {
super.viewDidLoad()
textField.text = strSaveText
// Do any additional setup after loading the view.
}
#IBAction func buttonDone(sender: UIButton)
{
if (self.delegate) != nil
{
delegate?.saveText(textField.text)
self.dismissViewControllerAnimated(true, nil)
}
}
}
just to point out
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
return .none
}
not woking properly on ios 12 /xcode 11, at least for popover tableview controller
The call below works
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}

Resources