I have a ViewController in my Storyboard which works like an alert (with a title, a message, and two buttons).
I would like to encapsulate it to be able to use it anywhere in my code, like this :
let alert = CustomAlertViewController(title: "Test", message: "message de test.", view: self.view, delegate: self)
self.present(alert, animated: false, completion: nil)
My problem is that the IBOutlets are not initialised...
My CustomAlertViewController :
public protocol CustomAlertProtocol {
func alertAccepted()
}
class CustomAlertViewController: UIViewController {
var delegate :CustomAlertProtocol? = nil
var parentView :UIView?
var blurScreenshot :SABlurImageView?
var alertTitle :String? = nil
var alertMessage :String? = nil
#IBOutlet weak var oAlertView: UIView!
#IBOutlet weak var oAlertTitle: UILabel!
#IBOutlet weak var oAlertMessage: UILabel!
//MARK: - Main
public convenience init(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) {
self.init()
self.alertTitle = title
self.alertMessage = message
self.delegate = delegate
self.parentView = view
}
override func viewDidLoad() {
oAlertTitle.text = self.alertTitle
oAlertMessage.text = self.alertMessage
}
#IBAction func onAcceptButtonPressed(_ sender: AnyObject) {
delegate?.alertAccepted()
}
}
Set the Custom Class property of your View Controller to CustomAlertViewController
and Storyboard ID to whatever you want - e.g. CustomAlertViewControllerIdentifier in the Identity Inspector of the InterfaceBuilder.
And then instantiate it like following:
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
guard let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as? CustomAlertViewController else {
return
}
edit:
You can then put that code in a class function like:
extension CustomAlertViewController {
class func instantiateFromStoryboard(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) -> CustomAlertViewController {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as! CustomAlertViewController
vc.title = title
vc.message = message
vc.view = view
vc.delegate = delegate
return vc
}
}
and then use like:
let myCustomAlertViewController = CustomAlertViewController.instantiateFromStoryboard(title: "bla", ...)
Related
Goal: In a separate storyboard that is loaded via a storyboard reference in the main.storyboard, in a pageViewController acting as the initial view controller, I want to initialize an array object of viewControllers via the function .instantiateViewController(identifier:).
Issue: The last viewController I'm trying to instantiate as a constant is not loading. The error - *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load the scene view controller for identifier 'FinalVC''"
All other viewControllers in this storyboard load fine. This last view controller has a correct custom class linked and a unique storyboard identifier.
Debugging: I've created a breakpoint where this view controller is instantiated and noticed in the debugging console all other view controller objects load as "BillyCues.repeatViewController + unique identification number" while this last vc loads as "UIViewController + 0x000000000000000". It's almost as if this vc is not a part of the app bundle or referenced correctly but it's there when I search in the directory.
Debugging console screen
Things I've tried that did not work:
Check to see if another vc has the same identifier
Clean the build folder
Check "Use Storyboard ID" in the identity inspector
let finalVC = storyBoard.instantiateViewController(identifier: "FinalVC") as! FinalViewController
Restart Xcode
Create a brand new view controller with a different storyboard identifier using the same custom class
Removed all connections from buttons and labels in the last vc
Made sure all storyboard references in main.storyboard has the correct storyboard linked
Conclusion: All my googling has led to other developers encountering the error about NIBs or tableviews not necessarily a view controller. If my vc has a correct custom class and unique identifier the error should not occur. If anyone can offer guidance I'd appreciate it; I'm dumbfounded.
I hope I've asked for help in an appropriate structure but please let me know if more code or screenshots are needed.
PageViewController Code
import UIKit
class LauncherViewController: UIPageViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setViewControllers([viewControllerList[0]], direction: .forward, animated: false, completion: nil)
// Do any additional setup after loading the view.
}
private var viewControllerList: [UIViewController] = {
let storyBoard = UIStoryboard.cueCreation
let firstVC = storyBoard.instantiateViewController(identifier: "CueNameVC")
let secondVC = storyBoard.instantiateViewController(identifier: "DueDateVC")
let thirdVC = storyBoard.instantiateViewController(identifier: "IconVC")
let fourthVC = storyBoard.instantiateViewController(identifier: "IconColorVC")
let fifthVC = storyBoard.instantiateViewController(identifier: "RepeatVC")
let finalVC = storyBoard.instantiateViewController(identifier: "FinalVC") as! FinalViewController
return [firstVC, secondVC, thirdVC, fourthVC, fifthVC, finalVC]
}()
var selectedReminderBill: CueObject?
public var currentIndex = 0
static var cueName: String = ""
static var cueDate: Date = Date()
static var cueIcon: Data = Data()
static var iconColor:String = "14CC7F"
static var repeatMonthly: Bool = false
// Navigation button functions below to move to the next or previous page
func pushNext() {
if currentIndex + 1 < viewControllerList.count {
self.setViewControllers([self.viewControllerList[self.currentIndex + 1]], direction: .forward, animated: true, completion: nil)
currentIndex += 1
}
}
func pullBack() {
print(currentIndex)
if currentIndex - 1 < viewControllerList.count {
self.setViewControllers([self.viewControllerList[self.currentIndex-1]], direction: .reverse, animated: true, completion: nil)
currentIndex -= 1
}
}
}
FinalViewController Code
import UIKit
import UserNotifications
import RealmSwift
class FinalViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
cueName.text = LauncherViewController.cueName
dueDate.text = CueLogic.convertPaymentDateToString(for: LauncherViewController.cueDate)
iconBackgroundView.backgroundColor = colorLogic.colorWithHexString(hexString: LauncherViewController.iconColor)
cueIcon.image = UIImage(data: LauncherViewController.cueIcon)
repeatsMonthly.text = repeatMonthlyToString
}
override func viewDidLoad() {
super.viewDidLoad()
cueName.layer.cornerRadius = 15
cueName.clipsToBounds = true
iconBackgroundView.layer.cornerRadius = 20
iconBackgroundView.clipsToBounds = true
dueDate.layer.cornerRadius = 15
dueDate.clipsToBounds = true
repeatsMonthly.layer.cornerRadius = 15
repeatsMonthly.clipsToBounds = true
backButton.layer.cornerRadius = 15
backButton.clipsToBounds = true
saveButton.layer.cornerRadius = 15
saveButton.clipsToBounds = true
// Do any additional setup after loading the view.
}
let colorLogic = ColorLogic()
let realm = try! Realm()
weak var delegate: HomeScreenDelegate?
var launcher = LauncherViewController()
var repeatMonthlyToString: String {
get {
if LauncherViewController.repeatMonthly == true {
return "Repeats Monthly: Yes"
} else {
return "Repeats Monthly: No"
}
}
}
#IBOutlet var cueName: UILabel!
#IBOutlet var dueDate: UILabel!
#IBOutlet var saveButton: UIButton!
#IBOutlet var backButton: UIButton!
#IBOutlet var iconBackgroundView: UIView!
#IBOutlet var cueIcon: UIImageView!
#IBOutlet var repeatsMonthly: UILabel!
#IBAction func dismissButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func backButtonTapped(_ sender: Any) {
if let pageController = parent as? LauncherViewController {
pageController.pullBack()
}
}
#IBAction func saveButtonTapped(_ sender: Any) {
// Request authorization from the user to allow notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {success, error in
if success {
// schedule test
} else if let error = error {
print("error occured \(error)")
}
})
let newCue = CueObject()
let launcherVC = LauncherViewController.self
newCue.name = launcherVC.cueName
newCue.paymentDate = launcherVC.cueDate
newCue.icon = launcherVC.cueIcon
newCue.iconColor = launcherVC.iconColor
newCue.repeatsMonthly = launcherVC.repeatMonthly
NotificationLogic.scheduleLocalAlertForBill(named: newCue.name, due: newCue.paymentDate, repeatsMonthly: newCue.repeatsMonthly)
saveToDB(for: newCue)
delegate?.loadCuesFromRealm()
self.dismiss(animated: true, completion: nil)
}
func saveToDB(for cue: CueObject) {
do {
try realm.write({
realm.add(cue)
})
} catch {
print("Error - \(error)")
}
}
}
protocol HomeScreenDelegate: AnyObject {
func loadCuesFromRealm()
}
Extension I wrote in another viewController
extension UIStoryboard {
static let onboarding = UIStoryboard(name: "Onboarding", bundle: nil)
static let main = UIStoryboard(name: "Main", bundle: nil)
static let cueCreation = UIStoryboard(name:"CueCreation", bundle: nil)
}
Identity Inspector
Main Storyboard References
I'd do a few things as part of cleanup to start debugging the actual issue. In the storyboard extension, I'd rather use a static function to reference the view controller.
extension UIStoryboard {
class func createFinalVC() -> FinalViewController? {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FinalVC") as? FinalViewController)
}
}
And for implementing it, I'd use in the view controller presenting FinalViewController:
private func createCreateFinalVC() -> FinalViewController? {
return UIStoryboard.createFinalVC()
}
And finally pushing it into the view,
if let finalVC = createCreateFinalVC() {
yourNavController?.pushViewController(finalVC, animated: true)
}
Solution
I began a process of elimination and started to comment out all of the code in my FinalVC class. I learned that this line of code var launcher = LauncherViewController() was triggering the crash.
Given my limited beginner knowledge I don't know why this would cause a crash; I can only assume that Xcode was trying to initialize two LauncherViewControllers with identical identifier numbers or something along those lines.
nil Delegate between two ViewController with two different Bundle using swift 4 (commented in second code)
here is my code :
First ViewController :
class FirstVC : UIViewController, MerchantResultObserver{
var secVC = SecondVC()
override func viewDidLoad() {
secVC.delegate = self
let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
let controller = storyboard.instantiateInitialViewController()
self.present(controller!, animated: true, completion: nil)
secVC.initSecondVC(data)
}
func Error(data: String) {
print("-------------Error Returned------------- \(data)")
}
func Response(data: String) {
print("-------------Response Returned------------- \(data)")
}
}
Second ViewController :
public class SecondVC: UIViewController {
public weak var delegate: MerchantResultObserver!
public func initSecondVC(_ data : String){
print(data)
}
#IBAction func sendRequest(_ sender: UIButton) {
delegate?.Response(data: “dataReturnedSuccessfully”) // delegate is nil //
dismiss(animated: true, completion: nil) // returned to FirstVC without returning “dataReturnedSuccessfully” //
}
}
public protocol MerchantResultObserver: class{
func Response(data : String)
func Error(data : String)
}
Any help would be appreciated
var secVC = SecondVC()
and
let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
let controller = storyboard.instantiateInitialViewController() as? SecondVC
These both are different instances.
You can assign a delegate to the controller, like
controller.delegate = self
It will call the implemented delegate methods in First View Controller.
Full Code.
let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
if let controller = storyboard.instantiateInitialViewController() as? SecondVC {
//Assign Delegate
controller.delegate = self
//It's not init, but an assignment only, as per your code.
controller.initSecondVC(data)
self.present(controller, animated: true, completion: nil)
}
One more thing, Don't present View in ViewDidLoad. You can put a code in some button or in a delay method.
So I have XIB View and View Controller. I want when a button in my XIB clicked (didTapTryAgain Button), the called a function from my view controller. Then I tried to create a protocol and delegate for the class. But it still won't called my function. Here's my XIB view class:
import UIKit
protocol ErrorMessageDelegate {
func refresh(_sender: AnyObject)
}
class ErrorMessage: UIView {
#IBOutlet weak var imageViewError: UIImageView!
#IBOutlet weak var labelError: UILabel!
#IBOutlet weak var buttonTryAgain: UIButton!
static weak var shared: ErrorMessage?
var delegate: ErrorMessageDelegate?
static var message: String?
override func awakeFromNib() {
ErrorMessage.shared = self
labelError.text = ErrorMessage.message
}
#IBAction func didTapTryAgain(_ sender: UIButton) {
delegate?.refresh(_sender: buttonTryAgain)
}
}
And here's my View Controller class:
import Foundation
class BaseViewController: UIViewController, ErrorMessageDelegate {
func refresh(_sender: AnyObject) {
print("I hope my function work here")
}
var uiView = UIView();
override func viewDidLoad() {
super.viewDidLoad()
ErrorMessage.shared?.delegate = self
}
func getErrorMessage(message:String) {
super.viewDidLoad()
Dialog.dismiss()
ErrorMessage.message = message
guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
self.view.addSubview(viewErrorMessage)
}
}
I'm following this answer for my code, and it still not working. Is anyone know how to do it? Thank you!
Your problem is that you set the delegate for a shared instance here
ErrorMessage.shared?.delegate = self / here shared?. is nil
but here
guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
self.view.addSubview(viewErrorMessage)
you create a separate instance and add it
You need
var viewErrorMessage:ErrorMessage! // add to the vc
viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as! ErrorMessage
viewErrorMessage.delegate = self
self.view.addSubview(viewErrorMessage)
Also completely git rid of
static weak var shared: ErrorMessage?
Simply use this code then your delegate method will be call.
func getErrorMessage(message:String) {
ErrorMessage.message = message
guard let viewErrorMessage = Bundle.main.loadNibNamed("ErrorMessage", owner: self, options: nil)?.first as? ErrorMessage else { return}
viewErrorMessage.delegate = self
self.view.addSubview(viewErrorMessage)
}
and call method where ever you want to open the popup
getErrorMessage(message: "Test Message")
Im having a problem with the UIView margins when Instantiating it on the callback function. When the view is instantiated like this it looks normal:
let viewController = UIStoryboard(name: "Tracking", bundle: nil).instantiateViewControllerWithIdentifier("tracking") as! CarrierTrackingVC
elDrawer.mainViewController = viewController
Normal Screen
But when I instantiate in the api request callback like this, the view looks weird
TrackingController().getTruckTrack("7RZEY3VP") { (response, errs) in
if !self.requestErrors(errs) {
let truckTrack = TruckTrack(json:response["truck_track"].description)
let viewController = UIStoryboard(name: "Tracking", bundle: nil).instantiateViewControllerWithIdentifier("tracking") as! CarrierTrackingVC
elDrawer.mainViewController = viewController
}
}
Weird margins Screen
I would like to know why that happen and any clue of how could I fix it.
Thanks.
EDIT: This is the full code:
import Foundation
import UIKit
import KYDrawerController
import PKHUD
import JLToast
class MenuVC: UITableViewController {
#IBOutlet weak var fullnameLBL: UILabel!
#IBOutlet weak var profileTypeLBL: UILabel!
#IBOutlet weak var usernameLBL: UILabel!
#IBOutlet weak var profilePicIMG: RoundedImage!
#IBOutlet weak var homeLBL: UILabel!
#IBOutlet weak var servicesLBL: UILabel!
#IBOutlet weak var signOutLBL: UILabel!
#IBOutlet weak var trackingLBL: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initContent()
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: PICTURE, options: NSKeyValueObservingOptions.New, context: nil)
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: NAME, options: NSKeyValueObservingOptions.New, context: nil)
if let url = SessionManager.sharedInstance.picture {
profilePicIMG.imageFromUrl(url)
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == PICTURE {
if let url = object as? String {
profilePicIMG.imageFromUrl(url)
}
}
if keyPath == NAME {
usernameLBL.text = object as? String
}
}
deinit {
NSUserDefaults.standardUserDefaults().removeObserver(self, forKeyPath: PICTURE)
NSUserDefaults.standardUserDefaults().removeObserver(self, forKeyPath: NAME)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath newIndexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(newIndexPath, animated: true)
let elDrawer = (self.navigationController?.parentViewController as! KYDrawerController)
switch newIndexPath.row {
//Profile info
case 0:
break
//Home
case 1:
elDrawer.mainViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MainNavigation")
//Services
case 2:
elDrawer.mainViewController = UIStoryboard(name: "Services", bundle: nil).instantiateViewControllerWithIdentifier("services")
case 3:
TrackingController().getTruckTrack("7RZEY3VP") { (response, errs) in
if !self.requestErrors(errs) {
let truckTrack = TruckTrack(json:response["truck_track"].description)
let viewController = UIStoryboard(name: "Tracking", bundle: nil).instantiateViewControllerWithIdentifier("tracking") as! CarrierTrackingVC
viewController.truckTrack = truckTrack
elDrawer.mainViewController = viewController
}
}
/*let viewController = UIStoryboard(name: "Tracking", bundle: nil).instantiateViewControllerWithIdentifier("tracking") as! CarrierTrackingVC
viewController.truckTrack = TruckTrack()
elDrawer.mainViewController = viewController*/
default:
signnOut()
}
elDrawer.setDrawerState(.Closed, animated: true)
}
func signnOut() {
HUD.show(.LabeledProgress(title: NSLocalizedString("SIGNING_OUT", comment: ""), subtitle: nil))
UserController().signOut { (response, err) in
HUD.hide()
self.changeRootViewControllerWithIdentifier("start",storyboard: "Main")
}
}
func initContent() {
fullnameLBL.text = SessionManager.sharedInstance.userFullName
usernameLBL.text = SessionManager.sharedInstance.username
profileTypeLBL.text = SessionManager.sharedInstance.profileType
}
}
EDIT: viewController is a UITabBarController, each Tab contains a Navigation Controller and it's child is a View Controller.
It looks as if the vc's view is being covered by the navigation bar, which, prior to OS 6 or 7, was the default. I can't explain why the behavior would appear in one instantiation context vs the other, but you fix by setting explicitly with:
let viewController = // yada yada
viewController.edgesForExtendedLayout = UIRectEdgeNone
EDIT if I'm right that viewController is a navigation view controller, then we need it's root to adjust the edge property...
let viewController = /*yada yada*/ as! UINavigationController
let rootVC = viewController.viewControllers[0]
rootVC.edgesForExtendedLayout = UIRectEdgeNone
I am opening another ViewController using this:
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)
let homeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "IssueViewController")
self.present(homeViewController, animated: true, completion: nil)
Along with this, I need to pass a Person object and a String value to the 2nd ViewController.
struct Person {
var Name: String
var Details: String
}
What changes do I need to do to attach a Person object to my existing code?
EDIT: This is the 2nd ViewController
I am trying to retrieve the values from this view
class IssueViewController: UIViewController {
var person: Person = Person();
override func viewDidLoad() {
super.viewDidLoad()
}
}
//changes in first controller
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main",bundle:Bundle.main)
let homeViewController: IssueViewController = mainStoryboard.instantiateViewController(withIdentifier: "IssueViewController") as! IssueViewController
homeViewController.person = Person(Name:"ABC",Details:"XYZ")
homeViewController.bindWithData(yourStringObject)
self.present(homeViewController, animated: true, completion: nil)
//changes in second view controller
class IssueViewController: UIViewController {
var person: Person = Person(Name:"",Details:"");
override func viewDidLoad() {
super.viewDidLoad()
print(person.Name)
print(person.Details)
}
func bindWithData(yourStringObject:String){
//your code here.
}
}