Protocol Doesn't Send Value to Other VC - swift

That is my footerView called FooterTableViewCell. I have this protocol called SurveyAnswerTableViewCellDelegate. It's parent is AddQuestionViewController.
When I tap on the footerView I trigger #IBActtion.
#objc protocol SurveyAnswerTableViewCellDelegate: AnyObject {
func textSaved(_ text: String)
}
class FooterTableViewCell: UITableViewHeaderFooterView {
var parentVC: AddQuestionViewController!
#IBAction func addNewTapped(_ sender: Any) {
print("tapped")
let newTag = model.tag + 1
parentVC.addNewAnswer()
}
This button action triggers AddQuestionViewController
class AddQuestionViewController: SurveyAnswerViewDelegate, UITextFieldDelegate, UITableViewDelegate, SurveyAnswerTableViewCellDelegate {
var answers: [SurveyAnswerModel] = []
var savedText : String = ""
static var delegate: SurveyAnswerTableViewCellDelegate?
I try creating an empty string and append a new answer to my array. But this text here is always "".
func addNewAnswer() {
let newAnswer = SurveyAnswerModel(answer: savedText, tag: 0)
self.answers.append(newAnswer)
self.tableView.reloadData()
}
func textSaved(_ text: String) {
savedText = text
}
The textfield I try to read is inside SurveyAnswerTableViewCell while setting up the cell inside the tableview I call setup function.
class SurveyAnswerTableViewCell: UITableViewCell {
#IBOutlet weak var textField: UITextField!
weak var delegate: SurveyAnswerTableViewCellDelegate?
var parentVC: AddQuestionViewController!
func setup() {
if let text = self.textField.text {
self.delegate?.textSaved(textField.text!)
}
}
extension AddQuestionViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as SurveyAnswerTableViewCell
cell.parentVC = self
cell.setup()
return cell
}
How can I successfully send that text to AddQuestionViewController so it appends a new answer with correct string

There are a few things keeping this from working.
You are calling SurveyAnswerTableViewCell's setup() function directly after dequeuing the cell for reuse. It has not yet (re)appeared on the screen at that point, so the user has not had a chance to enter anything into the text field.
You don't currently set the delegate property of SurveyAnswerTableViewCell to anything, so even if the textfield had valid input, the delegate would be nil and delegate?.textSaved(textField.text!) wouldn't do anything.
Both of the previous points mean that the value of AddQuestionViewController .savedText never gets updated from the empty string. So when addNewAnswer() tries to read it, it will always see that empty string.
Rather than reading the text field when the cell is dequeued, it would make more sense to save the text field value when the user is done typing.
To do that, conform the cell to UITextFieldDelegate and implement the textFieldDidEndEditing(_:) method. From within that method you can then call the delegate method you already have to save the text. Make sure the delegate property on the cell has been set by the VC, or else this won't do anything!
The VC itself should not have a delegate property of type SurveyAnswerTableViewCellDelegate. It serves as the delegate, rather than having one. If this doesn't quite make sense, I would recommend reviewing some online resources on the delegate pattern.
So make sure the ViewController conforms to SurveyAnswerTableViewCellDelegate and then set the cell's delegate value to the VC. The cellForRowAt function should then look something like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as SurveyAnswerTableViewCell
cell.delegate = self
return cell
}
As a side note, neither the footer nor the cell should have a reference to the parent view controller. as a general rule it is good to avoid subviews being aware of their parent views. Things get unnecessarily complicated when there is two-way knowledge sharing between components, and it makes the subview much less reusable. I would recommend making a delegate for the footer as well, and removing the parentVC property from both the footer and the cell.

Here's what it looks like is happening:
Button tapped
addNewTapped(_:) invoked
addNewAnswer() invoked
newAnswer is appended to answers
tableView.reloadData() invoked
Cells are regenerated with new/empty textfields (so delegate.textSaved is never invoked)
so I'm not sure what you're trying to do, but here's what I figure are a couple possible routes:
store UITextFields separately and add them into table cells so they're not removed by a table reload
conform AddQuestionViewController to UITextFieldDelegate and set it as the textfields' delegate to observe textfield texts changing (and if you're only using 1 textfield, you could set savedText there)

Related

Text is jumbled in custom cell

I'm trying to read data from CoreData into a custom cell. This is just a test app before I try moving to the real app that I've been working on. The data is there - I can print it to the console and see it. For some reason, even with constraints, all of the data is laid on top of each other in the cell. Can anyone see what's going on with this?
I've created constraints to keep the cells where they should be, but when the data is loaded from my 'show data' button, the data is laid on top of each other.
Here is my custom cell class:
import UIKit
class CustomCellClass: UITableViewCell {
#IBOutlet weak var txtNameLabel: UILabel!
#IBOutlet weak var txtAgeLabel: UILabel!
}
Here is the ShowData class: (partial)
class ShowData: UIViewController, NSFetchedResultsControllerDelegate {
#IBOutlet weak var personTableView: UITableView!
let appDelegate = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var personData = [Person]()
// Read the data
override func viewDidLoad() {
super.viewDidLoad()
personTableView.delegate = self
personTableView.dataSource = self
loadItems()
}
func loadItems() {
let request : NSFetchRequest<Person> = Person.fetchRequest()
do {
personData = try appDelegate.fetch(request)
} catch {
print("couldn't load")
}
}
}
extension ShowData : UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return personData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let person = personData[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "personNameAge", for: indexPath) as! CustomCellClass
cell.txtNameLabel?.text = person.name
cell.txtAgeLabel?.text = String(person.age)
return cell
}
Here is a screenshot of the tableview while running:
Edit:
I just deleted the app from the simulator and tried to rerun - now there isn't any data in the cells.
Just to clarify for other readers, as can be seen in your screenshot, the rows in your table are separated as expected but the different fields in each cell, what one might call the columns, are on top of one another.
You say that you have created constraints to keep the cells where they should be, I'm not sure what you mean by that. What you need is constraints for the fields within each cell – what I call intra-cell constraints. Either you have not added these constraints, or there is a mistake in them which causes all fields to be drawn at the left.
To show you what I mean, let's use the example of a little workout app of mine which has, in each table cell, from left to right, a Perform button, an Edit button, a Name field and a Duration field. The screenshot below shows, in the big yellow box, the intra-cell constraints. If you are using a storyboard, the problem with your app must be in that area. If you are not using a storyboard, the problem must be in the equivalent code (or lack of it).
Just to let everyone know. The issue is resolved. I removed the table view cell from the project, readded, and readded the constraints. Everything is working now. I'm not sure where the problem was, but I noticed I had weird wrapping happening. I moved one of the labels to the other side of the cell and constrained it to the right side, and the other to the left side. When I ran the app, the text appeared to word wrap. I decided to delete the cell and readd and relink my outlets. It worked the first time...

How do I get the row number of the cell where the UITextView was edited?

I have a UITextView inside each cell of a UITableView
I am using Core Data to save data which is typed in the UITextView
I would like to save the text typed in UITextView once the user is done editing it
I have added UITextViewDelegate to my TableViewCell class
I am using Notifications to post the new text to the TableViewController
I am able to get the new text to the TableViewController but I don't know how to get the row number of the cell that contained the textview wherein the text was typed. I need to know the row number (or the object in that row) to update the correct NSManagedObject.
What I have Tried:
I was thinking about using tags but since I need to constantly add and delete rows it wouldn't be the best approach
I have tried using DidSelectedRowAtIndexPath but it doesn't get triggered while the
user taps the UITextView (UITextView covers up to 80% of the one cell)
In the TableViewCell class, I have:
func textViewDidEndEditing(_ textView: UITextView) {
// Post notification
let userInfo = [ "text" : textView.text]
NotificationCenter.default.post(
name: UITextView.textDidEndEditingNotification,
object: nil,
userInfo: userInfo as [AnyHashable : Any])
}
In the TableViewController, I have:
//Subscribe
NotificationCenter.default.addObserver(self,
selector: #selector(textEditingEnded(notification:)),
name: UITextView.textDidEndEditingNotification,
object: nil)
#objc func textEditingEnded(notification:Notification) {
guard let text = notification.userInfo?["text"] as? String else {return}
print ("text: \(text)")
}
Don't hesitate to ask for more details.
I'll appreciate every bit of help I can get!
Create a property of the NSManagedObject type in the table view cell.
In Interface Builder connect the delegate of the text view to the cell.
In the controller pass the appropriate data source item in cellForRowAt to the cell.
Delete the observer and instead of posting a notification change the attribute in the NSManagedObject instance directly and save the context.
As NSManagedObject instances are reference types the changes will persist.
I hope you can have variable inside your UITableViewCell subclass for certain item
var item: Item?
then in cellForRowAt set certain item for certain cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ...
...
cell.item = array[indexPath.row]
...
}
now you can implement UITextViewDelegate to your cell subclass and you can use method textViewDidEndEditing for handling when user is done with typing
class YourCell: UITableViewCell {
...
var item: Item?
...
override func awakeFromNib() {
yourTextView.delegate = self
}
}
extension YourCell: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
... // here save text and here you can use variable `item`
}
}

Swift add button to UICollectionViewCell that opens new controller

I have a UICollectionViewCell header on a UICollectionViewController, and I've added a button to it. I would like for the button, when clicked, to push a new view controller atop the current one. The problem is that the button doesn't have access to the navigation controller of the UICollectionViewController, so I there's no way to directly push a controller from, say, a connector to the buttn (that I know of). Is there any way to achieve this? Maybe something can be overriden, such as a collectionView function. Thanks!
If you just want to process the cell selection there is a handy method in the UICollectionViewDelegate that you can implement to get the index path of the pressed cell.
If your goal is to have a custom button inside the cell (or maybe even several) you can use delegation pattern to retrieve user actions to your controller to than process in any way, including pushing/presenting new controllers. Assign the controller's instance (the one managing the collection view) to the delegate member of your cell.
Define a protocol that I would call something like MyCustomCellDelegate (replace MyCustomCell with a more appropriate name for your case). Something like MyCustomCellDelegate: class { func didPressButtonX() }
Declare an optional delegate property in your cell subclass. weak var delegate: MyCustomCellDelegate?
Implement your delegate protocol by the class you want to respond to button presses (or any other interactions defined by your protocol).
Every time you create/dequeue a cell for your UICollectionView to use you set the delegate property to the view controller managing the collection view. cell.delegate = self (if done inside the view controller itself).
After receiving the UI event inside your custom cell use your delegate property to retrieve the action to the controller (or with ever object you used when assigning the property). Something like: delegate?.didPressButtonX()
In your class that implements MyCustomCellDelegate use the method to push the new controller.
Below I will provide sample code that should give more details on the implementation of the proposed solution:
// In your UICollectionViewCell subclass file
protocol MyCustomCellDelegate: class {
func didPressButtonX()
func didPressButtonY()
}
MyCustomCell: UICollectionViewCell {
weak var delegate: MyCustomCellDelegate?
#IBOutlet var buttonX: UIButton!
#IBOutlet var buttonY: UIButton!
#IBAction func didPressButtonX(sender: Any) {
delegate?.didPressButtonX()
}
#IBAction func didPressButtonY(sender: Any) {
delegate?.didPressButtonY()
}
}
// Now in your UICollectionViewController subclass file
MyCustomCollectionViewController: UICollectionViewController {
// ...
override func collectionView(UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier identifier: "YourCellIdentifierGoesHere", for indexPath: indexPath) as! MyCustomCell
// In here we assign the delegate member of the cell to make sure once
// an UI event occurs the cell will call methods implemented by our controller
cell.delegate = self
// further cell setup if needed ...
return cell
}
}
// In order for the instance of our controller to be used as cell's delegate
// we implement the protocol that we defined earlier in the cell file
extension MyCustomCollectionViewController: MyCustomCellDelegate {
func didPressButtonX() {
print("X button was pressed")
// now lets finally push some new controller
let yourNextCoolViewController = UIViewController()
self.push(yourNextCoolViewController, animated: true)
// OR if you are using segues
self.performSegue(withIdentifier: "YourSegueIdentifierGoesHere", sender: self)
}
func didPressButtonY() {
print("Y button was pressed")
}
}

Swift3 Multiple buttons dynamic coding to trigger event

I have multiple buttons. Each button contains a language label.
I want to make it so that when users tap on the button, the selected language label changes its value according to the button tapped.
The selected language outlet is called SelectedLangText.
A simple solution would be to create multiple Action outlets for each button and set the value of SelectedLangText label. However, if there would be 100 buttons, that would be bad coding.
I'm not sure how to approach this situation in Swift 3 coming from web development.
I prefer using the delegate design pattern when it comes to solving an issue like that for it I find it to be a much cleaner approach than just a mass amount of #IBActions
1- Create a Language class
import Foundation
class Language {
var id: Int
var name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
2- Create the custom cell in the storyboard or nib and then add the appropriate outlets and actions. And then you create a Delegate protocol for it
import UIKit
protocol CustomCellDelegate: class {
func customCell(newLanguageSelected language: Language)
}
class CustomCell: UITableViewCell {
var language: Language!
#IBOutlet weak var languageTextLabel: UILabel!
weak var delegate: CustomCellDelegate?
func setupCustomCell(withLanguage language: Language){
self.language = language
self.languageTextLabel.text = self.language.name
}
#IBAction func buttonPressed(sender: UIButton){
delegate?.customCell(newLanguageSelected: self.language)
}
}
3- Finally add the implementation in the cellForRow method of the UITableViewDataSource and add the implementation of the delegate in the UITableViewController class
import UIKit
class YourTableViewController: UITableViewController{
var languages: [Language] = []
//implement the other methods in the dataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuse", for: indexPath) as! CustomCell
cell.delegate = self
cell.setupCustomCell(withLanguage: languages[indexPath.row])
return cell
}
}
extension YourTableViewController: CustomCellDelegate{
func customCell(newLanguageSelected language: Language) {
//Do what you will with the language
}
}
Good luck
You can add Tags to each button and Set same IBAction for all buttons.
First in your method get the language based on the button.
Now use loop(go with for loop as you will need proper index for each button) and get all buttons from its tag and set language tag.
A bit complex at glance, but will solve your problem and good solution in my eye.
for index in 101...103 {
let myBtn = self.view.viewWithTag(index) as! UIButton
myBtn.setTitle("localisedtitle string", for: .normal)
}

Using the contentView property on a custom tableView cell (being passed as a header) how to prevent it from nullifying the custom attributes?

For example here is my custom cell:
protocol SectionHeaderTableViewCellDelegate {
func didSelectUserHeaderTableViewCell(sectionHeader: SectionHeaderTableViewCell, selected: Bool, type: Type)
}
class SectionHeaderTableViewCell: UITableViewCell {
#IBOutlet weak var labelContainerView: LabelContainerView!
#IBOutlet weak var sectionTitleLabel: UILabel!
#IBOutlet weak var plusButton: UIButton!
var type: Type?
var delegate: SectionHeaderTableViewCellDelegate?
var dog: Dog?
let sections = [Type.Meals, Type.Exercise, Type.Health, Type.Training, Type.Misc]
}
extension SectionHeaderTableViewCell {
#IBAction func plusButtonPressed(sender: AnyObject) {
if let type = type {
delegate?.didSelectUserHeaderTableViewCell(self, selected: plusButton.selected, type: type )
}
}
In my controller if I add a return of header.contenView I get the desired results of the header staying in place but unfortunately it nullifies the button included in the custom header preventing it from being called. Otherwise if I simply just return header the button on the custom header cell works as expected but the header moves with the row being deleted which is obviously unsightly and not what I want.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = tableView.dequeueReusableCellWithIdentifier("sectionHeader") as? SectionHeaderTableViewCell else { return UITableViewCell() }
header.delegate = self
header.updateDogWithGender(dog)
header.type = header.sections[section]
header.sectionTitleLabel.text = header.sections[section].rawValue
return header.contentView
}
moving headers
In case anyone runs into a similar situation the solution was to create a Nib file and customize it as you see fit. Create a nib file by going to File -> New File -> iOS -> User Interface -> and selecting View. Create Nib file. I added my views and buttons to get the look I wanted. customize Nib. From there I changed the custom cell class to be UITableViewHeaderFooterView instead and reconnected my outlets and actions to the new Nib file.
class SectionHeaderView: UITableViewHeaderFooterView {... previous code from above }
Back in the controller update the viewForHeaderInSection function to load a nib instead :
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = NSBundle.mainBundle().loadNibNamed("SectionHeader", owner: self, options: nil).first as? SectionHeaderView
header?.delegate = self
header?.updateDogWithGender(dog)
header?.type = header?.sections[section]
header?.sectionTitleLabel.text = header?.sections[section].rawValue
return header
}
By the way we declared the property first at the end of the loadNibNamed property because it returns an array of AnyObjects and since my Nib file only contains one UIView that houses a label and a button I only needed the first and only item in the array. Thanks to my mentor James for figuring this out!