I have a UIPickerView that I am subclassing, which works great. However, I have a method that I need to call to "reset" the UIPicker from the UIViewController in which it's being viewed. However, it never fires. How do I call func resetPicker() from another view controller?
import Foundation
import UIKit
class ScoreClockPicker: UIPickerView {
//PickerView
let timerMinutesArray = Array(00...20)
let timerSecondsArray = Array(00...59)
let periodArray = ["1st", "2nd", "3rd", "OT", "SO"]
//Picker return values
var numberOfRowsInComponentReturnValue = 0
var titleForRowReturnValue = ""
var widthForComponentReturnValue = ""
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
self.dataSource = self
}
func resetPicker() {
print("resetPicker")
self.selectRow(0, inComponent: 0, animated: true)
self.selectRow(0, inComponent: 1, animated: true)
self.selectRow(0, inComponent: 3, animated: true)
}
}
extension ScoreClockPicker: UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
numberOfRowsInComponentReturnValue = periodArray.count
} else if component == 1 {
numberOfRowsInComponentReturnValue = timerMinutesArray.count
} else if component == 2 {
numberOfRowsInComponentReturnValue = 1
} else if component == 3 {
numberOfRowsInComponentReturnValue = timerSecondsArray.count
}
return numberOfRowsInComponentReturnValue
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
var componentWidth = 0
if component == 0 {
componentWidth = 140
} else if component == 1 {
componentWidth = 40
} else if component == 2 {
componentWidth = 30
} else if component == 3 {
componentWidth = 40
}
return CGFloat(componentWidth)
}
}
extension ScoreClockPicker: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("didSelectRow")
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
titleForRowReturnValue = periodArray[row]
} else if component == 1 {
titleForRowReturnValue = String(describing: timerMinutesArray[row])
} else if component == 2 {
titleForRowReturnValue = ":"
} else if component == 3 {
titleForRowReturnValue = String(format: "%02d",timerSecondsArray[row])
}
return titleForRowReturnValue
}
}
EDIT:
The following doesn't work from the viewController calling the ScoreClockPicker:
import UIKit
class ScoreClockViewController: UIViewController {
#IBOutlet weak var resetButton: UIButton!
#IBOutlet weak var okButton: UIButton!
var picker: ScoreClockPicker?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Hide the Navigation Bar
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
//#IBOutlet
#IBAction func reset(_ sender: Any) {
print("reset")
picker?.resetPicker() //Call the ScoreClockPicker
// picker?.selectRow(0, inComponent: 0, animated: true)
// picker?.selectRow(0, inComponent: 1, animated: true)
// picker?.selectRow(0, inComponent: 3, animated: true)
}
#IBAction func ok(_ sender: Any) {
}
}
From your code you haven't initialized the picker object that you are trying to use in button action. So simply initialized the picker before using it.
If you are making outlet of ScoreClockPicker then
#IBOutlet var picker: ScoreClockPicker!
OR you can initialized picker in viewDidLoad
self.picker = ScoreClockPicker()
Related
I am trying to get image from camera and show in imageview using swift 3.0 but it is showing white background only. Image is uploaded to my server successfully. On iPAD it is not even opening the camera app. below is my code: I am new to swift to please let me know what mistake i ma doing.
import UIKit
import Alamofire
import SwiftyJSON
import AlamofireImage
class RadiologyViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate{
#IBOutlet weak var indicator1: UIActivityIndicatorView!
#IBOutlet weak var name : UILabel!
#IBOutlet weak var mobile: UILabel!
#IBOutlet weak var gender: UILabel!
#IBOutlet weak var age : UILabel!
#IBOutlet weak var indicator4: UIActivityIndicatorView!
#IBOutlet weak var indicator3: UIActivityIndicatorView!
#IBOutlet weak var indicator2: UIActivityIndicatorView!
#IBOutlet weak var pic4text: UITextView!
#IBOutlet weak var pic3text: UITextView!
#IBOutlet weak var pic2text: UITextView!
#IBOutlet weak var pictext1: UITextView!
// WHICH SHOW BUTTON YOU WANT TO SHOW YOU HAVE TO CHANGE HEIGHT CONSTRAINT //
// conPic1height = conPic1height - 20 - UN HIDE BUTTON BY TAKING ITS OUTLET//
#IBOutlet weak var conPic1height: NSLayoutConstraint!
#IBOutlet weak var conPic2height: NSLayoutConstraint!
#IBOutlet weak var conPic3height: NSLayoutConstraint!
#IBOutlet weak var conPic4height: NSLayoutConstraint!
#IBOutlet weak var pic4: UIImageView!
#IBOutlet weak var pic3: UIImageView!
#IBOutlet weak var pic2: UIImageView!
#IBOutlet weak var pic1: UIImageView!
#IBOutlet weak var complain: UILabel!
#IBOutlet weak var explain : UILabel!
#IBOutlet weak var date : UILabel!
#IBOutlet weak var btnShowPic4: UIButton!
#IBOutlet weak var btnShowPic3: UIButton!
#IBOutlet weak var btnShowPic2: UIButton!
#IBOutlet weak var btnShowPic1: UIButton!
var patient : Patients? = nil;
var username : String? = nil;
var picNumber : Int = 0;
var pic1path : String = "";
var pic2path : String = "";
var pic3path : String = "";
var pic4path : String = "";
var strLabel = UILabel()
var indicator = UIActivityIndicatorView()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
if patient != nil {
name.text = patient?.patientName;
age.text = "Age: "+(patient?.patientAge)!;
gender.text = "Gender: "+(patient?.patientGender)!;
mobile.text = "Mobile: "+(patient?.patientMobile)!;
date.text = "Date: "+(patient?.patientDate)!;
complain.text = "Complaint: " + "\(self.makeComplainText(complain: (patient?.patientComplaint)!))";
explain.text = "Explain: "+(patient?.patientExplainComplaint)!;
}
let defaults1 = UserDefaults.standard
let user = defaults1.object(forKey: "user") as? NSData
let responseData = NSKeyedUnarchiver.unarchiveObject(with: user! as Data) as? ResponseModel
if responseData != nil {
if responseData?.profile != nil {
username = responseData?.profile[0].userName;
}
}
pictext1.delegate = self
pic2text.delegate = self
pic3text.delegate = self
pic4text.delegate = self
pic1path = (patient?.patientPic1)!;
pic2path = (patient?.patientPic2)!;
pic3path = (patient?.patientPic3)!;
pic4path = (patient?.patientPic4)!;
pictext1.text = patient?.patientPictxt1;
pic2text.text = patient?.patientPictxt2;
pic3text.text = patient?.patientPictxt3;
pic4text.text = patient?.patientPictxt4;
let tapFirstGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped1(_:)))
pic1.isUserInteractionEnabled = true
pic1.addGestureRecognizer(tapFirstGestureRecognizer)
let tapSecondGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped2(_:)))
pic2.isUserInteractionEnabled = true
pic2.addGestureRecognizer(tapSecondGestureRecognizer)
let tapThirdGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped3(_:)))
pic3.isUserInteractionEnabled = true
pic3.addGestureRecognizer(tapThirdGestureRecognizer)
let tapFourGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped4(_:)))
pic4.isUserInteractionEnabled = true
pic4.addGestureRecognizer(tapFourGestureRecognizer)
if patient?.patientPic1 != "" {
pic1.image = nil;
setImage(imageview: pic1, url: (patient?.patientPic1)!,indicator:indicator1)
showFirstButton(show: false)
} else {
showFirstButton(show: true)
indicator1.isHidden = true
}
if patient?.patientPic2 != "" {
pic2.image = nil;
showSecondButton(show: false)
setImage(imageview: pic2, url: (patient?.patientPic2)!,indicator:indicator2)
} else {
showSecondButton(show: true)
indicator2.isHidden = true
}
if patient?.patientPic3 != "" {
pic3.image = nil;
showThreeButton(show: false)
setImage(imageview: pic3, url: (patient?.patientPic3)!,indicator:indicator3)
} else {
showThreeButton(show: true)
indicator3.isHidden = true
}
if patient?.patientPic4 != "" {
pic4.image = nil;
showFourButton(show: false)
setImage(imageview: pic4, url: (patient?.patientPic4)!,indicator:indicator4)
} else {
showFourButton(show: true)
indicator4.isHidden = true
}
let tapKeuboardDismissGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(_:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapKeuboardDismissGestureRecognizer)
// Do any additional setup after loading the view.
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
func dismissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func imageTapped1(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 1;
showActionSheet()
}
}
func imageTapped2(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 2;
showActionSheet()
}
}
func imageTapped3(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 3;
showActionSheet()
}
}
func imageTapped4(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 4;
showActionSheet()
}
}
func camera()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = false
myPickerController.sourceType = UIImagePickerControllerSourceType.camera
myPickerController.cameraCaptureMode = .photo
myPickerController.modalPresentationStyle = .fullScreen
self.present(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
// if (UIDevice.current.userInterfaceIdiom == .pad) {
// let popover = actionSheet.popoverPresentationController
// popover?.sourceRect = self.view.bounds
// popover?.sourceView = self.pic1
// popover?.permittedArrowDirections = .any
// self.present(actionSheet, animated: true, completion: nil)
// } else {
self.present(actionSheet, animated: true, completion: nil)
//}
}
#IBAction func btnpic3Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic3path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic4Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic4path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic1Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic1path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic2Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic2path
self.present(viewcontroller, animated: false)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if picNumber == 1 {
pic1.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 2 {
pic2.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 3 {
pic3.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else {
pic4.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
}
self.dismiss(animated: true, completion: nil)
}
func uploadImage(image:UIImage) -> Void {
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "uploding image");
let imgData = UIImageJPEGRepresentation(image, 0.2)!
var path :String = "";
let parameters = ["username": username]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "images",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
}
},
to:"http://www.dentalsa.net/api/api.php?method=radiaolog_image_update")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
self.hideLoading()
let value = response.result.value
let jsonResponse = JSON(value)
let status = jsonResponse["status"].stringValue
let message = jsonResponse["message"].stringValue
if status == "false" {
self.showAlerError(titleText: "Error", messagetext: message);
}
path = jsonResponse["path"].stringValue
if self.picNumber == 1 {
self.pic1path = path
} else if self.picNumber == 2 {
self.pic2path = path
} else if self.picNumber == 3 {
self.pic3path = path
} else if self.picNumber == 4 {
self.pic4path = path
}
print("ImagePath"+path)
}
case .failure(let encodingError):
print(encodingError)
}
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeComplainText(complain:String) -> String {
let characters = Array(complain.characters);
var data="";
if characters[0] == "1" {
data += "Check-Up, ";
}
if characters[1] == "1" {
data += "Teeth Cleaning, ";
}
if characters[2] == "1" {
data += "Periodontal Treatment, ";
}
if characters[3] == "1" {
data += "Dental Fillings, ";
}
if characters[4] == "1" {
data += "Prothesis, ";
}
if characters[5] == "1" {
data += "Extraction, ";
}
if characters[6] == "1" {
data += "Hollywoods smile, ";
}
if characters[7] == "1" {
data += "Children's Teeth, ";
}
if characters[8] == "1" {
data += "Bleaching, ";
}
return data;
}
#IBAction func saveClick(_ sender: UIButton) {
let netowrk = NetworkCall();
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "Please wait")
netowrk.radiologyUpdate(username: username!,patientId: (patient?.patientID)!,picText1: pictext1.text!,picText2: pic2text.text!,picText3: pic3text.text!,picText4: pic4text.text!,pic1:pic1path,pic2:pic2path,pic3:pic3path,pic4:pic4path) { responseObject in
self.hideLoading()
if responseObject.status == "true" {
print("Success view controller");
self.showAlerError(titleText: "Success", messagetext: "Details saved Successfully");
} else {
self.showAlerError(titleText: "Error", messagetext: responseObject.message!);
}
return
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
func showLoading(title: String) {
strLabel.removeFromSuperview()
indicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
indicator.startAnimating()
effectView.addSubview(indicator)
effectView.addSubview(strLabel)
view.addSubview(effectView)
}
func setImage(imageview :UIImageView,url:String,indicator:UIActivityIndicatorView) -> Void {
Alamofire.request("http://www.dentalsa.net"+url).responseImage { response in
if let image = response.result.value {
indicator.isHidden = true
imageview.image = image
}
}
}
func hideLoading() {
self.effectView.removeFromSuperview()
//indicator.stopAnimating()
}
func showAlerError(titleText:String,messagetext:String) {
let alertController = UIAlertController(title: titleText, message:
messagetext, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
#IBAction func backClick(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
}
func showFirstButton(show :Bool){
//conPic1height.constant = 150
btnShowPic1.isHidden = show
self.view.layoutIfNeeded()
}
func showSecondButton(show :Bool){
//conPic1height.constant = 150
btnShowPic2.isHidden = show
self.view.layoutIfNeeded()
}
func showThreeButton(show :Bool){
//conPic1height.constant = 150
btnShowPic3.isHidden = show
self.view.layoutIfNeeded()
}
func showFourButton(show :Bool){
//conPic1height.constant = 150
btnShowPic4.isHidden = show
self.view.layoutIfNeeded()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I need to capture image from camera and gallery on both iphone and iPad. I don't know what is the issue which i am facing here.
I'm trying to create two tableViews in one UIViewController. But when I'm trying to assign value to UILabel, getting an error: fatal error: unexpectedly found nil while unwrapping an Optional value
I wonder why, I have almost the same code for TableViewController with one tableView and it works with no issues. It looks like these UI Labels are not initialized when trying to assign value to it. But don't understand how to fix it.
It fails here:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
if tableView == self.guestsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestAtTableTableViewCell
if let guestsTable = guestsTableFetchedResultsController?.object(at: indexPath) {
print(guestsTable.guestName) // works fine, prints the value
print(cell.guestNameLabel.text) //fails here with error fatal error: unexpectedly found nil while unwrapping an Optional value
cell.guestNameLabel.text = guestsTable.guestName
cell.openTimeLabel.text = String(describing: guestsTable.openTime)
cell.cellDelegate = self
}
}
else if tableView == self.ordersTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath)
//to be done
}
// Configure the cell...
return cell!
}
Full code of this class:
import UIKit
import CoreData
class TableUIViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CellWithButtonDelegate {
//The following two variables will not be nil because prepare for segue will set them
var tableName: String?
var table: TablesTable? = nil
fileprivate var currentTableSession: TableSessionTable? {
get {
let tableSessionTable = TableSessionTable()
return tableSessionTable.getCurrentTableSession(table: table!)
}
}
fileprivate var guestsTableFetchedResultsController: NSFetchedResultsController<GuestsTable>?
fileprivate var ordersTableFetchedResultsController: NSFetchedResultsController<OrdersTable>?
#IBOutlet weak var tableNameLabel: UILabel!
#IBOutlet weak var tableCapacityLabel: UILabel!
#IBOutlet weak var tableCountOfGuestsLabel: UILabel!
#IBOutlet weak var tableDescriptionTextView: UITextView!
#IBAction func closeTableButtonPressed(_ sender: UIButton) {
}
#IBOutlet weak var guestsTableView: UITableView!
#IBOutlet weak var ordersTableView: UITableView!
#IBAction func addGuestButtonPressed(_ sender: UIButton) {
let guestsTable = GuestsTable()
let tablesTable = TablesTable()
let table = Table(tableName: tableName!, tableCapacity: 0, locationX: nil, locationY: nil, tableImage: nil)
try? guestsTable.addNewGuest(table: tablesTable.getOrCreateTable(table: table))
updateUI()
}
#IBAction func addOrderButtonPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
guestsTableView.dataSource = self
guestsTableView.delegate = self
guestsTableView.register(GuestAtTableTableViewCell.self, forCellReuseIdentifier: "guestCell")
ordersTableView.dataSource = self
ordersTableView.delegate = self
ordersTableView.register(UITableViewCell.self, forCellReuseIdentifier: "orderCell")
updateUI()
}
func didPressButton(table: TablesTable) {
}
private func updateUI () {
let tableView = guestsTableView
let context = AppDelegate.viewContext
let request : NSFetchRequest<GuestsTable> = GuestsTable.fetchRequest()
request.predicate = NSPredicate(format: "table= %#", currentTableSession!)
request.sortDescriptors = [NSSortDescriptor(key: "guestName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
guestsTableFetchedResultsController = NSFetchedResultsController<GuestsTable>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
try? guestsTableFetchedResultsController?.performFetch()
tableView?.reloadData()
}
private func updateUI1 () {
let tableView = ordersTableView
let context = AppDelegate.viewContext
let request : NSFetchRequest<OrdersTable> = OrdersTable.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "menuItem", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))]
ordersTableFetchedResultsController = NSFetchedResultsController<OrdersTable>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
try? ordersTableFetchedResultsController?.performFetch()
tableView?.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
if tableView == self.guestsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "guestCell", for: indexPath) as! GuestAtTableTableViewCell
if let guestsTable = guestsTableFetchedResultsController?.object(at: indexPath) {
print(guestsTable.guestName) // works fine, prints the value
print(cell.guestNameLabel.text) //fails here with error fatal error: unexpectedly found nil while unwrapping an Optional value
cell.guestNameLabel.text = guestsTable.guestName
cell.openTimeLabel.text = String(describing: guestsTable.openTime)
cell.cellDelegate = self
}
}
else if tableView == self.ordersTableView {
cell = tableView.dequeueReusableCell(withIdentifier: "orderCell", for: indexPath)
//to be done
}
// Configure the cell...
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == self.guestsTableView {
return guestsTableFetchedResultsController?.sections?.count ?? 1
}
else if tableView == self.ordersTableView {
return ordersTableFetchedResultsController?.sections?.count ?? 1
}
else {return 1}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.guestsTableView {
if let sections = guestsTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
}
else {
return 0
}
}
else if tableView == self.ordersTableView {
if let sections = ordersTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
}
else {
return 0
}
}
else {return 0}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == self.guestsTableView {
if let sections = guestsTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
}
else {
return nil
}
}
else if tableView == self.ordersTableView {
if let sections = ordersTableFetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
}
else {
return nil
}
}
else {return nil}
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if tableView == guestsTableView {
return guestsTableFetchedResultsController?.sectionIndexTitles
}
else {
return ordersTableFetchedResultsController?.sectionIndexTitles
}
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if tableView == guestsTableView {
return guestsTableFetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
else if tableView == ordersTableView {
return ordersTableFetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
else {return 0}
}
}
And full code of UITableViewCell class:
import UIKit
class GuestAtTableTableViewCell: UITableViewCell {
weak var cellDelegate: CellWithButtonDelegate?
#IBOutlet weak var guestNameLabel: UILabel!
#IBOutlet weak var openTimeLabel: UILabel!
#IBAction func didPressButton(_ sender: UIButton) {
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I guess you have a xib for your UITableViewCell register the xib instead of the class.
Use the following:
guestsTableView.register(UINib.init(nibName: "GuestAtTableTableViewCell", bundle: nil), forCellReuseIdentifier: "guestCell")
As you have created a prototype cell in the storyboard itself you should select the cell in the storyboard and set its identifier there. Next remove the register line from your code for guestCell. It should work
Hello everybody I'm trying to build a simple one view program to call and navigate a voice menu, I cannot get the UserDefaults to properly save between closing of the app. I've also had issue with getting text to display in the UITextField, I would like for it to display if saved on launch, here is a description of vars:
UserInput - text field for employee ID (what needs saving)
Switch - if Save it is 1 save data, if 0 do not
Submit - submit button that should save the data and call.
This is my first iPhone app and any help would be much appreciated!
enter code here
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var UserInput: UITextField!
var SaveIt = true
var employID = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.UserInput.delegate = self;
UserInput.keyboardType = .numberPad
if let current_eid = UserDefaults.standard.string(forKey: "emp_ID") {
UserInput.text = current_eid
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadDefaults() {
let defaults = UserDefaults.standard
if let UserInput = defaults.string(forKey: "emp_ID") {
print(UserInput)
} else {
// focus on the text field if it's empty
UserInput.becomeFirstResponder() }
UserInput.text = defaults.object(forKey: "emp_ID") as! String?
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
#IBAction func Switch(_ sender: UISwitch) {
if (sender.isOn == true) {
SaveIt = true
}
else{
SaveIt = false
}
}
#IBAction func Submit(_ sender: Any) {
if (SaveIt) {
let defaults = UserDefaults.standard
defaults.set(UserInput.text, forKey: "emp_ID")
defaults.synchronize()
}
let phone = "telprompt://1888247889pppp" + UserInput.text! + "p1p1p1p1";
let url = URL(string:phone)!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else { UIApplication.shared.openURL(url)
}
}
}
So I am new to iOS development. I am trying to make a page swipe functionality like an image carousel or like an app tutorial, and I'm Running into a Thread 1: signal SIGABRT error. in the log is states 'Can not cast value of type 'ViewController' to 'UIPageViewController'
not sure you need the entire code.
my problem line is:
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "contentViewController") as! UIPageViewController
help will be greatly appreciated.
class ViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController: UIPageViewController!
var pageTitles: NSArray!
var pageImages: NSArray!
override func viewDidLoad() {
self.pageTitles = NSArray(objects: " By Request","Subscription Plan","Flex Plan","Everyday Plan", "Welocme")
self.pageImages = NSArray(objects: "page1","page2","page3","page4","page5")
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "contentViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(index: 0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRect(x: 0, y:0, width: Int(self.view.frame.width), height: Int(self.view.frame.size.height - 60))
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func loginAction(_ sender: AnyObject) {
}
#IBAction func signupAction(_ sender: AnyObject) {
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
var vc: ContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "pageViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
// MARK: - Page Vuew Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if ((index == 0) || (index == NSNotFound)) {
return nil
}
index -= 1
return self.viewControllerAtIndex(index: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound) {
return nil
}
index += 1
if (index == self.pageTitles.count) {
return nil
}
return self.viewControllerAtIndex(index: index)
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
I am having difficulties converting two sections of code from Swift 2 to Swift 3
The working Swift 2 Code Block was
func showRoute(routes: [MKRoute], time: NSTimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(routes[i])
directionsArray += [(locationArray[i].textField.text!,
locationArray[i+1].textField.text!, routes[i])]
}
displayDirections(directionsArray)
printTimeToLabel(time)
}
Swift 3 has converted this to
func showRoute(routes: [MKRoute], time: TimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(route: routes[i])
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
}
displayDirections(directionsArray: directionsArray)
printTimeToLabel(time: time)
}
This produces an error on the line
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
Cannot convert value of type '[(startingAddress: String, endingAddress: String, route: MKRoute)]' to expected argument type 'inout _'
If anyone can help i would really appreciate it
Just need
directionsArray += [(startingAddress : locationArray[i].textField!.text!,
endingAddress : locationArray[i+1].textField!.text!,
route : routes[i])]
I saw your question, but There are no answers. And, That is not only one problem.
Here is full body of ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
#IBOutlet weak var sourceField: UITextField!
#IBOutlet weak var destinationField1: UITextField!
#IBOutlet weak var destinationField2: UITextField!
#IBOutlet weak var topMarginConstraint: NSLayoutConstraint!
#IBOutlet var enterButtonArray: [UIButton]!
var originalTopMargin: CGFloat!
let locationManager = CLLocationManager()
var locationTuples: [(textField: UITextField?, mapItem: MKMapItem?)]!
var locationsArray: [(textField: UITextField?, mapItem: MKMapItem?)] {
var filtered = locationTuples.filter({ $0.mapItem != nil })
filtered += [filtered.first!]
return filtered
}
override func viewDidLoad() {
super.viewDidLoad()
originalTopMargin = topMarginConstraint.constant
locationTuples = [(sourceField, nil), (destinationField1, nil), (destinationField2, nil)]
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()
}
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
}
#IBAction func getDirections(_ sender: AnyObject) {
view.endEditing(true)
performSegue(withIdentifier: "show_directions", sender: self)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if locationTuples[0].mapItem == nil ||
(locationTuples[1].mapItem == nil && locationTuples[2].mapItem == nil) {
showAlert("Please enter a valid starting point and at least one destination.")
return false
} else {
return true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let directionsViewController = segue.destination as! DirectionsViewController
directionsViewController.locationArray = locationsArray
}
#IBAction func addressEntered(_ sender: UIButton) {
view.endEditing(true)
let currentTextField = locationTuples[sender.tag-1].textField
CLGeocoder().geocodeAddressString(currentTextField!.text!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
var addresses = [String]()
for placemark in placemarks {
addresses.append(self.formatAddressFromPlacemark(placemark))
}
self.showAddressTable(addresses, textField:currentTextField!,
placemarks:placemarks, sender:sender)
} else {
self.showAlert("Address not found.")
}
} )
}
func showAddressTable(_ addresses: [String], textField: UITextField,
placemarks: [CLPlacemark], sender: UIButton) {
let addressTableView = AddressTableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
addressTableView.addresses = addresses
addressTableView.currentTextField = textField
addressTableView.placemarkArray = placemarks
addressTableView.mainViewController = self
addressTableView.sender = sender
addressTableView.delegate = addressTableView
addressTableView.dataSource = addressTableView
view.addSubview(addressTableView)
}
func formatAddressFromPlacemark(_ placemark: CLPlacemark) -> String {
return (placemark.addressDictionary!["FormattedAddressLines"] as! [String]).joined(separator: ", ")
}
#IBAction func swapFields(_ sender: AnyObject) {
swap(&destinationField1.text, &destinationField2.text)
swap(&locationTuples[1].mapItem, &locationTuples[2].mapItem)
swap(&self.enterButtonArray.filter{$0.tag == 2}.first!.isSelected, &self.enterButtonArray.filter{$0.tag == 3}.first!.isSelected)
}
func showAlert(_ alertString: String) {
let alert = UIAlertController(title: nil, message: alertString, preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK",
style: .cancel) { (alert) -> Void in
}
alert.addAction(okButton)
present(alert, animated: true, completion: nil)
}
// The remaining methods handle the keyboard resignation/
// move the view so that the first responders aren't hidden
func moveViewUp() {
if topMarginConstraint.constant != originalTopMargin {
return
}
topMarginConstraint.constant -= 165
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
func moveViewDown() {
if topMarginConstraint.constant == originalTopMargin {
return
}
topMarginConstraint.constant = originalTopMargin
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
enterButtonArray.filter{$0.tag == textField.tag}.first!.isSelected = false
locationTuples[textField.tag-1].mapItem = nil
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
moveViewUp()
}
func textFieldDidEndEditing(_ textField: UITextField) {
moveViewDown()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
moveViewDown()
return true
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(locations.last!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
let placemark = placemarks[0]
self.locationTuples[0].mapItem = MKMapItem(placemark:
MKPlacemark(coordinate: placemark.location!.coordinate,
addressDictionary: placemark.addressDictionary as! [String:AnyObject]?))
self.sourceField.text = self.formatAddressFromPlacemark(placemark)
self.enterButtonArray.filter{$0.tag == 1}.first!.isSelected = true
}
})
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}