Hi am trying to perform a segue by entering a specific word in a textfield.
So far my noob skills brought me to this.
I don't get an error, the simulator just crashes.
Any hints?
import UIKit
class CodewordVC: UIViewController, UITextFieldDelegate {
#IBOutlet weak var passWordInput: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
passWordInput.delegate = self
}
#IBAction func LosButton(_ sender: UIButton) {
//passwords
let realPassword1 = "rudi"
if passWordInput.text == realPassword1 {
self .performSegue(withIdentifier: "rudi", sender: self)
}
func dismissButton(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
Got it to work!
Can't really explain, but that would be the answer:
import UIKit
class CodewordVC: UIViewController, UITextFieldDelegate {
#IBOutlet weak var passWordInput: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
let realPassword1 = "rudi"
#IBAction func LosButton(_ sender: UIButton) {
passWordInput.delegate = self
//passwords
if self.passWordInput.text == realPassword1 {
DispatchQueue.main.async(){
self.performSegue(withIdentifier: "rudi", sender: self)
}
}
}
func dismissButton(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
Related
Hi im trying to pass data from one viewController to tableViewCell without using the segue, i tried with delegate and nsNotificationCenter but it did not work with me so, help me please.
this is my code for the view controller which i want to pass data from it ( imageViewSweet, LabelSweet )
import UIKit
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
passText = labelsweet.text
super.viewDidLoad()
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
}
and this is the code for the viewController which i want to display the image and the label from the swwetAndSalty4ViewController .
import UIKit
class cartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var priceLabel: UILabel!
var passText: String?
var cartItem = ""
#IBOutlet var cartTable: UITableView!
override func viewDidLoad() {
cartTable.delegate = self
cartTable.dataSource = self
// foodTable.separatorStyle = .none
view.backgroundColor = UIColor.init(red: 228/255, green: 230/255, blue: 234/255, alpha: 1)
navigationItem.title = "My Cart"
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cartItem.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
240
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as! cartTableViewCell
cell.layer.cornerRadius = 30
cell.layer.borderWidth = 15.0
cell.layer.borderColor = UIColor.white.cgColor
cell.cartImage.layer.masksToBounds = true
cell.cartImage.layer.cornerRadius = 2
cell.cartImage.translatesAutoresizingMaskIntoConstraints = false
cell.cartImage.contentMode = .scaleAspectFill
cell.cartLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
cell.cartLabel.textColor = .black
cell.cartLabel.translatesAutoresizingMaskIntoConstraints = false
cell.cartLabel.backgroundColor = .systemGray5
cell.cartLabel.text = ""
cell.cartImage.image = UIImage(named: "")
// cell.contentView.backgroundColor = .white
return cell
}
}
There you go, i've also organized your code:
First View Controller:
import UIKit
struct myVariables {
static var kinder: String! = nil
static var kinderImage: UIImage! = nil
}
class sweetAndSalty4ViewController: UIViewController {
#IBOutlet var imageViewSweet: UIImageView!
#IBOutlet var labelsweet: UILabel!
#IBOutlet var sweeetTable: UITableView!
var passText: String?
override func viewDidLoad() {
super.viewDidLoad()
passText = labelsweet.text
}
#IBAction func sendData(_ sender: UIButton) {
let sb = storyboard?.instantiateViewController(withIdentifier: "cartVC") as! cartViewController
sb.priceLabel = labelsweet
present(sb, animated: true, completion: nil)
}
func sendDataToMyVariables(kinder: String, kinderImage: UIImage) {
myVariables.kinder = kinder
myVariables.kinderImage = kinderImage
}
}
and then, after you send the variables you can use them anywhere in your code by doing
myVariables.kinder // get the string
myVariables.kinderImage // get the image
i'm running a query to Firebase and the results are displaying in a custom cell. The cell has a UIButton that when tapped it goes to another view controller where the user can enter info. The question i have is, how do i send the array in the custom cell to the next view controller? i need to send the array so i can reference the subcollection of info i'm going to add for each array. Segue is working properly, when i print to the console, the array is empty "nil". Any help is greatly appreciated.
Custom Cell
import UIKit
import Firebase
protocol PatCellCommentsDelegate {
func patCommentBtnTapped (ptcomments: [Comment])
}
class PatdataCell: UITableViewCell {
#IBOutlet weak var ptnameLbl: UILabel!
#IBOutlet weak var dobLbl: UILabel!
#IBOutlet weak var finLbl: UILabel!
#IBOutlet weak var officemdLbl: UILabel!
#IBOutlet weak var assignedmdLbl: UILabel?
#IBOutlet weak var appnameLbl: UILabel!
#IBOutlet weak var assigneddateLbl: UILabel!
#IBOutlet weak var roomnumberLbl: UILabel?
#IBOutlet weak var diagnosesLbl: UILabel!
#IBOutlet weak var reasonforadmitorconsultLbl: UILabel!
#IBOutlet weak var goalofhospitalizationLbl: UILabel!
#IBOutlet weak var seenoseeLbl: UILabel?
#IBOutlet weak var notestocboLbl: UILabel!
#IBOutlet weak var numCommentsLbl: UILabel!
#IBOutlet weak var hospitalLbl: UILabel!
#IBOutlet weak var teamLbl: UILabel!
#IBOutlet weak var addCommentBtn: UIButton!
var ptdata: PTData!
var ptcomments = [Comment]()
var delegate: PatCellCommentsDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
func configurePatDataCell(ptdata: PTData, delegate:
PatCellCommentsDelegate) {
self.ptdata = ptdata
self.delegate = delegate
ptnameLbl.text = ptdata.ptname
dobLbl.text = ptdata.dob
finLbl.text = ptdata.fin
officemdLbl.text = ptdata.officemd
assignedmdLbl?.text = ptdata.assignedmd
appnameLbl.text = ptdata.app
assigneddateLbl.text = ptdata.assigneddate
roomnumberLbl?.text = ptdata.room
diagnosesLbl.text = ptdata.diagnoses
reasonforadmitorconsultLbl.text = ptdata.reasonforadmitorconsult
goalofhospitalizationLbl.text = ptdata.goalofhospitalization
seenoseeLbl?.text = ptdata.seenosee
notestocboLbl.text = ptdata.notestocbo
numCommentsLbl.text = ptdata.comments
hospitalLbl.text = ptdata.hosp
teamLbl.text = ptdata.team
}
#IBAction func addCommentBtnTapped(_ sender: Any) {
//trying to send data to commentsVC from this cell
delegate?.patCommentBtnTapped(ptcomments: self.ptcomments)
}
}
View Controller
import UIKit
import Firebase
import SVProgressHUD
class PatdataVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, PatCellCommentsDelegate {
#IBOutlet weak var patDataTableView: UITableView!
var ptdatas = [PTData]()
var ptComments = [Comment]()
override func viewDidLoad() {
super.viewDidLoad()
patDataTableView.delegate = self
patDataTableView.dataSource = self
patDataTableView.rowHeight = 1150
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToComments" {
let commtsVC = segue.destination as! CommentsVC
commtsVC.ptComments = ptComments
SVProgressHUD.dismiss()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptdatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if tableView == patDataTableView {
let cell = tableView.dequeueReusableCell(withIdentifier:
"PatdataCell", for: indexPath) as? PatdataCell
cell!.configurePatDataCell(ptdata: ptdatas[indexPath.row],
delegate: self)
return cell!
}
return UITableViewCell()
}
func patCommentBtnTapped (ptcomments: [Comment]) {
self.ptComments = ptcomments
performSegue(withIdentifier: "goToComments", sender: self)
}
}
CommentsVC
import UIKit
import Firebase
import FirebaseFirestore
class CommentsVC: UIViewController, UITableViewDelegate,
UITableViewDataSource, CommentsDelegate {
#IBOutlet weak var commentTableView: UITableView!
#IBOutlet weak var addCommentTxt: UITextField!
#IBOutlet weak var keyboardView: UIView!
var ptComments = [Comment]()
var commentsPtData: Comment!
var commentRef: DocumentReference!
var username: String!
var commentListener : ListenerRegistration!
let firestore = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
commentTableView.dataSource = self
commentTableView.delegate = self
commentTableView.rowHeight = 110
//commentRef =
firestore.collection(PTLIST_REF).document(commentsPtData.documentId)
// if let name = Auth.auth().currentUser?.displayName{
// username = name
// }
self.view.bindToKeyboard()
}
override func viewDidAppear(_ animated: Bool) {
commentListener =
firestore.collection(PTLIST_REF).document(self.commentsPtData
.documentId)
.collection(COMMENTS_REF)
.order(by: TIMESTAMP, descending: false)
.addSnapshotListener({ (snapshot, error) in
guard let snapshot = snapshot else {
debugPrint("Error Fetching comments: \(Error.self)")
return
}
self.ptComments.removeAll()
self.ptComments = Comment.parseData(snapshot: snapshot)
self.commentTableView.reloadData()
})
}
override func viewDidDisappear(_ animated: Bool) {
commentListener.remove()
}
func commentOptionsTapped(commentsCellPtData: Comment) {
let alert = UIAlertController(title: "Edit Comment", message: "You
can delete or edit", preferredStyle: .actionSheet)
let deleteAction = UIAlertAction(title: "Delete Comment", style:
.default) { (action) in
self.firestore.runTransaction({ (transaction, errorPointer) ->
Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \ .
(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments -
1], forDocument: self.commentRef!)
let commentRef =
self.firestore.collection(PTLIST_REF).document(self
.commentsPtData.documentId).collection(COMMENTS_REF)
.document(commentsCellPtData.documentId!)
transaction.deleteDocument(commentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
alert.dismiss(animated: true, completion: nil)
}
}
}
let editAction = UIAlertAction(title: "Edit Comment", style:
.default) { (action) in
self.performSegue(withIdentifier: "toEditComment", sender:
(commentsCellPtData, self.commentsPtData))
alert.dismiss(animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel,
handler: nil)
alert.addAction(deleteAction)
alert.addAction(editAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
#IBAction func addCommentTapped(_ sender: Any) {
guard let commentTxt = addCommentTxt.text else { return }
firestore.runTransaction({ (transaction, errorPointer) -> Any? in
let ptListDocument: DocumentSnapshot
do {
try ptListDocument =
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
} catch let error as NSError {
debugPrint("Fetch Error: \(error.localizedDescription)")
return nil
}
guard let oldNumComments = ptListDocument.data()!
[NUM_COMMENTS] as? Int else { return nil }
transaction.updateData([NUM_COMMENTS : oldNumComments + 1],
forDocument: self.commentRef!)
let newCommentRef =
self.firestore.collection(PTLIST_REF).document((self
.commentsPtData.documentId)).collection(COMMENTS_REF).document()
transaction.setData([
COMMENT_TXT : commentTxt,
TIMESTAMP : FieldValue.serverTimestamp(),
USERNAME : self.username!,
USER_ID : Auth.auth().currentUser?.uid ?? ""
], forDocument: newCommentRef)
return nil
}) { (object, error) in
if let error = error {
debugPrint("transaction failed: \(error)")
} else {
self.addCommentTxt.text = ""
self.addCommentTxt.resignFirstResponder()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return ptComments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
"CommentCell", for: indexPath) as? CommentCell {
cell.configureCell(comment: ptComments[indexPath.row],
delegate: self)
return cell
}
return UITableViewCell()
}
}
In your source code ptcomments property in Custom Cell not set anywhere, it is empty in cell.
Please set correct value for ptcomments
UPDATE:
You try add line like self.comments = ptdata.commentsList to function configurePatDataCell
I'm trying to create a photo album via UIImagePicker into a CollectionView and cannot get it to segue to said photo again in a detailed UIViewController. Pulling my hair out and this is just a tutorial as I have just started coding!
Can anyone tell me what I'm doing wrong?
var testItems = [Person]()
#IBAction func addItem() {
addNewPerson()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
if let dest = segue.destination as? DetailsViewController,
let index = sender as? IndexPath {
dest.detailedImageHi = testItems[index.row]
}
}
}
THE NS OBJECT FILE IS AS FOLLOWS:
class Person: NSObject {
var imageHi: String
init(imageHi: String){
self.imageHi = imageHi
}
}
DetailsViewController:
class DetailsViewController: UIViewController {
var selection: String!
var detailedImageHi: UIImage!
#IBOutlet private weak var detailsLabel: UILabel!
#IBOutlet private weak var detailedImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
detailsLabel.text = selection
detailedImage.image = detailedImageHi
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var selectionImage: UIImageView!
}
I'm trying to append to an array via segue:
#IBOutlet weak var addTextTextField: UITextField!
#IBAction func addTextButton(_ sender: UIButton)
{
performSegue(withIdentifier: "addTextSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
let mainViewController = segue.destination as! MainViewController
mainViewController.array.append(addTextTextField.text!)
}
Its only appending to the array once, the next time I try, it overwrites the last entry. What is the reason for this?
When I press nextImage1 in the simulator, I get an error saying:
[Project_BodySwapp.ViewController nextImage:]: unrecognized selector sent to instance 0x7ffe4660a1e0'
import UIKit
class ViewController: UIViewController {
var imageNames1 = ["doghead","uk"]
var imageNames2 = ["macawLower","us"]
var pickedImage = String()
var currentImage = 0
#IBOutlet weak var displayImage: UIImageView!
//212x138
#IBOutlet weak var displayImage2: UIImageView!
//212x334
//BUTTON FUNCTIONALITY
//UPPER
#IBAction func randomizeImage(_ sender: Any) {
displayImage.image = UIImage(named: (produceRandomValue(imageNames1)))
}
#IBAction func nextImage1(_ sender: Any) {
currentImage += 1
displayImage.image = UIImage(named: imageNames1[currentImage])
}
#IBAction func previousImage1(_ sender: Any) {
}
//LOWER
#IBAction func randomizeImage2(_ sender: Any) {
displayImage2.image = UIImage(named: (produceRandomValue(imageNames2)))
}
func randomFromZero(to number: Int) -> Int {
return Int(arc4random_uniform(UInt32(number)))
}
func produceRandomValue(_ array: [String]) -> String {
let randomIndex = randomFromZero(to: array.count)
let pickedImage = imageNames1[randomIndex]
return pickedImage
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Any help would be greatly appreciated
Your button's action touchUpInside has been set as nextImage but in your code you don't have that. You have nextImage1 instead. Recheck the Connections Inspector.