storyboard?.instantiateViewController(withIdentifier: " ") as! viewcontroller - ios

I have as a Menu tableview in my custom navigation bar. If i click on one cell , it should take me to another view controller. But my app crashes when i click on it.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu_items.count //It has 5 values
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
cell.textLabel?.text = menu_items[indexPath.row]
cell.textLabel?.textColor = .white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = menu_items[indexPath.row]
if (item == "Patienten") {
tableView.removeFromSuperview()
let vc = self.storyboard?.instantiateViewController(withIdentifier: "patientView") as! patientViewVC //App crashes here
self.present(vc, animated: false, completion: nil)
} else if (item == "Mitarbeiter") {
} else if (item == "Kalender") {
} else if (item == "Tourenplanung") {
tableView.removeFromSuperview()
let vc = storyboard?.instantiateViewController(withIdentifier: "tour") as! tourVC //App crashes here
self.present(vc, animated: false, completion: nil)
}else if (item == "Abmelden") {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "loginvc") as! LoginVC //App crashes here
self.present(vc, animated: false, completion: nil)
}
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = colorLightGreen
}
}
I have many times verified all Identifier names and view controller names are correct.

Make sure you load a correct storyboard before instantiating the viewController.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = menu_items[indexPath.row]
if (item == "Patienten") {
tableView.removeFromSuperview()
let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "patientView") as! patientViewVC
self.present(vc, animated: false, completion: nil)
} else if (item == "Mitarbeiter") {
} else if (item == "Kalender") {
} else if (item == "Tourenplanung") {
tableView.removeFromSuperview()
let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "tour") as! tourVC //App crashes here
self.present(vc, animated: false, completion: nil)
}else if (item == "Abmelden") {
let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "loginvc") as! LoginVC //App crashes here
self.present(vc, animated: false, completion: nil)
}
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = colorLightGreen
}
StoryboardName above is the name of the storyboard that contains the patientViewVC, tourVC, LoginVC

A view controller in storyboard needs to have a custom class set in Identity inspector:
Then you can cast it to desired type. If all the view controllers are in the same storyboard, you can instantiate them with storyboard property of self. If they are in different storyboard, you have to instantiate UIStoryboard instance with corresponding name and use it.
Btw, why are you calling tableView.removeFromSuperview() after cell selection?

Related

How do I lock specific rows in a tableview through in-app purchases?

I have a tableview that requires users to pay in order to access its content. However, the entire tableview is locked. I would like to have, for example, the first two rows unlocked and the third row locked. I also have other tableviews with over 12 rows in them, but just posting this view controller for now. I am feeding in my data through an array, and I already have in-app purchases set up. Here is my current code:
import Foundation
import UIKit
class TrappingVC: UIViewController {
#IBOutlet weak var buildingTableView: UITableView!
#IBOutlet weak var settingsButtonItem: UIBarButtonItem!
var trapping: [CellObject] = []
var segueIdentifiers = ["a", "b"]
//VIEWDIDLOAD
override func viewDidLoad() {
super.viewDidLoad()
//LOAD ARRARYS
trapping = createBuildArray()
buildingTableView.delegate = self
buildingTableView.dataSource = self
self.buildingTableView.rowHeight = 100.0
buildingTableView.tableFooterView = UIView()
//CELL SEPARATORS
buildingTableView.layoutMargins = UIEdgeInsets.zero
buildingTableView.separatorInset = UIEdgeInsets.zero
buildingTableView.separatorColor = UIColor.black
buildingTableView.register(UINib.init(nibName: "TrappingCell", bundle: nil), forCellReuseIdentifier: "TrappingCell")
settingsButtonItem.image = UIImage(named: "Settings")
}
#IBAction func showSettingsClicked(_ sender: Any) {
performSegue(withIdentifier: "showSettings", sender: self)
}
//CREATE ARRAY OF BASIC LESSONS
func createBuildArray() -> [CellObject]{
var tempTrapping: [CellObject] = []
let trapping1 = CellObject(image: #imageLiteral(resourceName: "Yellow"), title: "Below")
let trapping2 = CellObject(image: #imageLiteral(resourceName: "Yellow"), title: "Side")
let trapping3 = CellObject(image: #imageLiteral(resourceName: "Yellow"), title: "Above")
tempTrapping.append(trapping1)
tempTrapping.append(trapping2)
tempTrapping.append(trapping3)
return tempTrapping
}
}
//TABLE
extension TrappingVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trapping.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let trappings = trapping[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "TrappingCell") as! TrappingCell
cell.trappingTitle.text = trappings.title
cell.trappingImage.image = trappings.image
if let purchased = UserDefaults.standard.value(forKey: "payment") as? Bool{
if purchased == true{
cell.lockedImage.isHidden = true
}else{
cell.lockedImage.isHidden = false
}
}else{
cell.lockedImage.isHidden = false
}
cell.layoutIfNeeded()
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let purchased = UserDefaults.standard.value(forKey: "payment") as? Bool{
if purchased == true{
performSegue(withIdentifier: segueIdentifiers[indexPath.row], sender: self)
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "UnlockContentVC")
self.navigationController?.pushViewController(controller, animated: true)
}
}else{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "UnlockContentVC")
self.navigationController?.pushViewController(controller, animated: true)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
I fixed it with the following code:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let purchased = UserDefaults.standard.value(forKey: "payment") as? Bool
if indexPath.row < 5 {
performSegue(withIdentifier: segueIdentifiers[indexPath.row], sender: self)
}
else if purchased == true {
performSegue(withIdentifier: segueIdentifiers[indexPath.row], sender: self)
} else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "UnlockContentVC")
self.navigationController?.pushViewController(controller, animated: true)
}
tableView.deselectRow(at: indexPath, animated: true)
}

Modal VC not open (Swift)

How can I make the VC appear also
I tried this but ms loaded clean without buttons and TextView.
let modalViewController = ClipboardViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
present(modalViewController, animated: true, completion: nil)
Example:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
self.navigationController!.pushViewController(self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as UIViewController, animated: true)
} else if indexPath.row == 1 {
// VC with animation
} else if indexPath.row == 2 {
self.navigationController!.pushViewController(self.storyboard!.instantiateViewController(withIdentifier: "Favorite") as UIViewController, animated: true)
} else if indexPath.row == 3 {
self.navigationController!.pushViewController(self.storyboard!.instantiateViewController(withIdentifier: "Settings") as UIViewController, animated: true)
}
}
let modalViewController = self.storyboard?.instantiateViewController(withIdentifier: "ClipboardViewController ID") as? ClipboardViewController
modalViewController?.modalPresentationStyle = .overCurrentContext
self.present(modalViewController!, animated: true, completion: nil)

Need to double tap on cell to present modally VC

I am generating table cell.
cell2 = settingsTableView.dequeueReusableCell(withIdentifier: "ModuleCell", for: indexPath) as! ModuleCell
It looks fine, the cell has tag = 2000.
In override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath), I am checking the tag end if tag == 2000 I want to present modal view. I am doing that in this way
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let modalView = storyboard.instantiateViewController(withIdentifier: "ModalView")
present(modalView, animated: true, completion: nil)
Then in modalView I have a button which should dismiss modalView, what's happening as expected.
#IBAction func saveAndClosePopup(_ sender: UIButton) {
UserDefaults.standard.removeObject(forKey: "ActiveCantachoOptions")
UserDefaults.standard.set(Modules.activeCantachoOptions, forKey: "ActiveCantachoOptions")
self.dismiss(animated: true, completion: nil)
}
However, when I want to immediately present modalView again, sometimes it's okay, but sometimes I need to hit two times on the cell, which should show modalView. After the first hit, there is no difference if I hit the cell again in 1 second or in 30 seconds. The modalView will appear after the second one. What is the cause?
Try this
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let modalView = storyboard.instantiateViewController(withIdentifier: "ModalView")
self.present(modalView, animated: true) {
tableView.deselectRow(at: indexPath, animated: false)
}
}

Swift / tableView pass data with instantiateViewControllerWithIdentifier

I have an array of BackendlessUsers filled within a tableView. How can I pass the user within the didSelectRowAtIndexPath function?
var deejays: [BackendlessUser] = []
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
**let user = deejays[indexPath.row]**
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("DJProfileAsUserVC") as! DJProfileAsUserVC
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(vc, animated: true, completion: nil)
}
}
Help is very appreciated.
Create a var user: DJProfileAsUserVC! in DJProfileAsUserVC and after that to this:
let user = deejays[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("DJProfileAsUserVC") as! DJProfileAsUserVC
vc.user = user

Push different UIView for each row of UITableView

I'm trying to push a new view when I select a row.
let identifiers:[String] = ["vc1", "vc2", "vc3", "vc4", "vc5"]
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let identifier = identifiers[indexPath.row]
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("\(identifier)") as! UINavigationController
self.presentViewController(vc, animated: true, completion: nil)
}
All the different views called with this tableView have their own class and Storyboard ID.
At the moment I get the error:
Could not cast value of type 'testApp.CalculatorViewController' to 'UINavigationController'
I think you are trying to cast UIViewController to UINavigationController.
Please try this. This may help you.
let identifiers:[String] = ["vc1", "vc2", "vc3", "vc4", "vc5"]
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let identifier = identifiers[indexPath.row]
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("\(identifier)") as! UIViewController
self.navigationController?.pushViewController(vc, animated: true, completion: nil)
}

Resources