I am trying to add search capabilities to the map based project I am working on in swift on XCode 6. I have added SearchDisplayController to my main view controller, which contains the map. I created a class called MapSearchDisplayController, which implements necessary methods. I also changed Custom Class property of the SearchDisplayController to MapSearchDisplayController in the storyboard.
In the storyboard, I dragged SearchDisplayController to my main view controller to create an IBOutlet. My main viewDidLoad for the main view controller looks like this:
class ViewController: UIViewController, CCHMapClusterControllerDelegate, MKMapViewDelegate, ADBannerViewDelegate {
#IBOutlet weak var mapSearchDisplayController1: MapSearchDisplayController!
#IBOutlet var mapSearchDisplayController: MapSearchDisplayController!
#IBOutlet weak var banner: ADBannerView!
#IBOutlet weak var mMap: MKMapView!
var clusterController:CCHMapClusterController?
let mMaxZoomLevelForClustering : Double = 13
let mMinUniqueLocationsForClustering : UInt = 1
var formatter = NSNumberFormatter()
var databasePath = NSString()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
banner.delegate = self
// Add button to navbar
var filterButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: nil)
self.navigationItem.leftBarButtonItem = filterButton
var aboutButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "aboutAction")
var searchButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchAction")
var rButtons : [UIBarButtonItem] = [aboutButton, searchButton]
self.navigationItem.rightBarButtonItems = rButtons
// Deal with Search Display Controller
self.mapSearchDisplayController.delegate = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchResultsDataSource = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchResultsDelegate = self.mapSearchDisplayController;
self.mapSearchDisplayController.searchBar.placeholder = "Search Destination";
self.mapSearchDisplayController.searchResultsTableView.delegate = self.mapSearchDisplayController
self.mapSearchDisplayController.searchResultsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
Issue 1: I had to add an additional mapSearchDisplayController1 - otherwise my mapSearchDisplayController was nil and I had an exception when I tried to to use it. Now when I have an additional variable mapSearchDisplayController1 (it is declared, but never used) it is not throwing exceptions and some functionality is working. Tried to add/remove weak, bt it did not make any difference. I can't figure out what have I missed that leads to this behavior.
Isse 2: Even bigger problem that I have, is that the instance variables of mapSearchDisplayController, which handles the search related functionality, are nil, its init method is not being invoked, but the functionality in the delegate methods work. So, data1 variable is nil, despite being initialized to hardcoded string array. Same goes for all other members, including googleAPIKey which is a constant. If shouldReloadTableForSearchString set data1 again data1 = ["1111", "222", "ZAAAA"] then it remains initialized, but if I assign data1 the value I get as a searchresult - it is lost. I would understand if the entire object was nil, but the methods are being invoked and working, it is just an instance variables and init which are not "working". Code below:
class MapSearchDisplayController: UISearchDisplayController, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, LPGoogleFunctionsDelegate
{
var data1 : [String]! = ["1111", "222", "ZAAAA"]
var googleFunctions : LPGoogleFunctions? = LPGoogleFunctions()
let googleAPIKey = "myKey"
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("In numberOfRowsInSection - \(data1.count)")
return self.data1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
println("In cellForRowAtIndexPath")
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if !(cell != nil) {
println("new cellForRow")
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
// Get the corresponding candy from our candies array
let candy = self.data1[indexPath.row]
// Configure the cell
cell!.textLabel.text = candy
cell!.detailTextLabel?.text = "Cell Details"
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
// Dismiss search display controller
self.active = false;
// Force selected annotation to be on map
}
func tableView(tableView: UITableView, numberOfSectionsInTableView indexPath: NSIndexPath) -> Int{
println("numberOfSectionsInTableView")
return 1
}
//MARK: Search methods
func filterContentForSearchText (searchText: String) {
println(searchText)
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
var length : Int32 = Int32(countElements(searchString))
if (countElements(searchString) < 3 ) {
println("Short searchString. Not enough info")
return false
}
data1 = []
if (googleFunctions == nil)
{
googleFunctions = LPGoogleFunctions()
googleFunctions!.sensor = false
googleFunctions!.delegate = self
googleFunctions!.googleAPIBrowserKey = "myKey"
}
println(googleFunctions?.googleAPIBrowserKey)
googleFunctions?.loadPlacesAutocompleteWithDetailsForInput(searchString, offset: length, radius: 0, location: nil, placeType: LPGooglePlaceTypeGeocode, countryRestriction: nil, successfulBlock: {(pd : [AnyObject]!) in
println("--------------GOOGLE search success")
for place in pd{
var pl = place as LPPlaceDetails
self.data1.append(pl.name)
println(pl.name)
}
}
, failureBlock: {(status : LPGoogleStatus) in
println("---- GOOGLE failed")
})
//data1 = ["1111", "222", "ZAAAA"]
return true
}
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController!){
controller.searchBar.showsCancelButton = true
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController!){
println("searchDisplayControllerWillEndSearch")
}
//MARK: LPGogleFunctions methods
override init() {
println("Initializing GoogleFunctions")
if (googleFunctions == nil){
googleFunctions = LPGoogleFunctions()
}
data1 = []
super.init()
googleFunctions!.sensor = false
googleFunctions!.delegate = self
googleFunctions!.googleAPIBrowserKey = "myKey"
}
}
Any help would be greatly appreciated.
I am answering my own question, in case someone ever has the same problem.
Issue #1 I resolved by deleteing both IBOutlets and re-adding them in the storyboard.
Issued #2: I did not made a call to searchResultsTableView.reloadData().
Since the network call was async, results were received in the lambda after the tableview was updated. Forcing an update sovled the problem.
Related
I'm a Swift beginner and I'm trying to make a simple app for ordering food. The user could add a new order by setting food name, price and serving. After adding an order, that order will be shown on the tableView as a FoodTableViewCell, and the user could change the serving with an UIStepper called stepper in each cell. Each order is a FoodItem stored in an array called foodList, and you can see all orders listed in a tableView in ShoppingListVC.
My problem is: When I press "+" or "-" button on stepper, my servingLabel doesn't change to corresponding value. I tried to use NotificationCenter to pass serving value to stepper, and store new value back to food.serving after stepperValueChanged with delegate pattern. However, there still seems to be some bugs. I've been kind of confused after browsing lots of solutions on the Internet. Any help is appreciated.
Update
I removed NotificationCenter and addTarget related methods as #Tarun Tyagi 's suggestion. Now my UIStepper value turns back to 1 whereas the servingLabels are showing different numbers of serving. Since NotificationCenter doesn't help, how can I connect the label and stepper value together? Is it recommended to implement another delegate?
Here are my codes(Updated on July 8):
FoodItem
class FoodItem: Equatable {
static func == (lhs: FoodItem, rhs: FoodItem) -> Bool {
return lhs === rhs
}
var name: String
var price: Int
var serving: Int
var foodID: String
init(name: String, price: Int, serving: Int) {
self.name = name
self.price = price
self.serving = serving
self.foodID = UUID().uuidString
}
}
ViewController
import UIKit
class ShoppingListVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
var foodList = [FoodItem]()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
...
for i in 1...5 {
let testItem = FoodItem(name: "Food\(i)", price: Int.random(in: 60...100), serving: Int.random(in: 1...10))
self.foodList.append(testItem)
}
}
// MARK: - Table view data source
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "foodCell", for: indexPath) as! FoodTableViewCell
let food = foodList[indexPath.row]
cell.nameLabel.text = food.name
cell.priceLabel.text = "$\(String(food.price)) / serving"
cell.servingLabel.text = "\(String(food.serving)) serving"
cell.stepper.tag = indexPath.row
cell.delegate = self
return cell
}
}
// MARK: - FoodTableViewCellDelegate Method.
extension ShoppingListVC: FoodTableViewCellDelegate {
func stepper(_ stepper: UIStepper, at index: Int, didChangeValueTo newValue: Double) {
let indexPath = IndexPath(item: index, section: 0)
guard let cell = tableView.cellForRow(at: indexPath) as? FoodTableViewCell else { return }
let foodToBeUpdated = foodList[indexPath.row]
print("foodToBeUpdated.serving: \(foodToBeUpdated.serving)")
foodToBeUpdated.serving = Int(newValue)
print("Value changed in VC: \(newValue)")
cell.servingLabel.text = "\(String(format: "%.0f", newValue)) serving"
}
}
TableViewCell
import UIKit
protocol FoodTableViewCellDelegate: AnyObject {
func stepper(_ stepper: UIStepper, at index: Int, didChangeValueTo newValue: Double)
}
class FoodTableViewCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBOutlet weak var servingLabel: UILabel!
#IBOutlet weak var stepper: UIStepper!
weak var delegate: FoodTableViewCellDelegate?
#IBAction func stepperValueChanged(_ sender: UIStepper) {
sender.minimumValue = 1
servingLabel.text = "\(String(format: "%.0f", sender.value)) serving"
// Pass the new value to ShoppingListVC and notify which cell to update using tag.
print("sender.value: \(sender.value)")
delegate?.stepper(stepper, at: stepper.tag, didChangeValueTo: sender.value)
}
override func awakeFromNib() {
super.awakeFromNib()
print(stepper.value)
}
}
Initially FoodTableViewCell is the ONLY target for UIStepper value changed (looking at #IBAction inside FoodTableViewCell).
When you dequeue a cell to display on screen, you call -
cell.stepper.addTarget(self, action: #selector(stepperValueChanged(_:)), for: .valueChanged)
which causes your ShoppingListVC instance to be added as an additional target every time a cellForRow call is executed.
Things to fix :
Remove all of your NotificationCenter related code from both classes.
Remove cell.stepper.addTarget() line as well.
This would give you a better idea of why it is happening this way. Update your question with these changes in case you still don't have what you want.
UPDATE
// Inside cellForRow
cell.stepper.value = food.serving
Cell Config:
protocol FoodTableViewCellDelegate: AnyObject {
func stepper(sender: FoodTableViewCell)
}
#IBAction func stepperButtonTapped(sender: UIStepper) {
delegate?.stepperButton(sender: self)
stepperLabel.text = "\(Int(countStepper.value))"
}
Controller Config:
cellForRow:
cell.countStepper.value = Double(foodList[indexPath.row].serving);
cell.stepperLabel.text = "\(Int(cell.countStepper.value))"
Delegate Method:
func stepperButton(sender: FoodTableViewCell) {
if let indexPath = tableView.indexPath(for: sender){
print(indexPath)
foodList[sender.tag].serving = Int(sender.countStepper.value)
}
}
Please check value stepper pod it will help you: Value stepper
Integrate value stepper pod and use below code for basic implementation.
import ValueStepper
let valueStepper: ValueStepper = {
let stepper = ValueStepper()
stepper.tintColor = .whiteColor()
stepper.minimumValue = 0
stepper.maximumValue = 1000
stepper.stepValue = 100
return stepper
}()
override func viewDidLoad() {
super.viewDidLoad()
valueStepper.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
#IBAction func valueChanged1(sender: ValueStepper) {
// Use sender.value to do whatever you want
}
Its simplify custom stepper implantation.Take outlet of value stepper view in table tableview and use it.
This question already has answers here:
How to pass data from child to parent view controller? in swift
(5 answers)
Closed 1 year ago.
I have a view controller, and inside that view controller I have a table view controller (see image here).
The program works as follows:
The user is typing someones email address, the table view is being updated as the user is typing.
Once the user is confident that the table is displaying the cell that he wants, he can click it and the info from the pressed cell "autocompletes" what the user was typing.
I have both view controllers (a table view and the regular one). I know how to send information from the viewController to the tableViewController, but I do not know how to to the reverse of that. Attached is the code for the viewController:
class PayViewController: UIViewController, STPAddCardViewControllerDelegate {
var finalAmount = ""
var toPay = 0.00
var successfullPayment = false
var payToUser = ""
var updatedBalance = ""
lazy var functions = Functions.functions()
var resultText = "" // empty
var input = ""
var email = ""
var sele = ""
#IBOutlet weak var forField: UITextField!
#IBOutlet weak var toField: UITextField!
#IBOutlet weak var amountLabel: UILabel!
//toField.addTarget(self, action: #selector(UsersTableViewController.textChanges(_:)), for: UIControl.Event.editingChanged)
var myTable:UsersTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
//var myTable:UsersTableViewController?
amountLabel.text = "$ \(finalAmount)"
myTable = self.children[0] as! UsersTableViewController
self.toField.addTarget(myTable, action: #selector(UsersTableViewController.textChanges(_:)), for: UIControl.Event.editingChanged)
}
#IBAction func paraFieldEdditingStarted(_ sender: Any) {
myTable!.filterContent(searchText:forField.text!)
//self.toField.addTarget(, action: #selector(UsersTableViewController.textChanges(_:)), for: UIControl.Event.editingChanged)
}
and the following is the code for the tableViewController
class UsersTableViewController: UITableViewController, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
//update the search results
filterContent(searchText: searchT)
}
#objc func textChanges(_ textField: UITextField) {
let text = textField.text! // your desired text here
// Now do whatever you want.
searchT = text
filterContent(searchText:textField.text!)
}
#IBOutlet var usersTableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var searchT = ""
var usersArray = [NSDictionary?]()
var filteredUsers = [NSDictionary?]()
var databaseRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
databaseRef = Database.database().reference()
let usersRef = databaseRef.child("users")
let query = usersRef.queryOrdered(byChild: "email")
query.observe(.childAdded, with: {(snapshot) in
self.usersArray.append((snapshot.value as? NSDictionary?)!)
//insert the rows
self.usersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1, section: 0)], with: UITableView.RowAnimation.automatic)
}) { (error) in
print(error.localizedDescription)
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if (self.searchT != ""){
return filteredUsers.count
}
return self.usersArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let user: NSDictionary
if ((searchT != "")){
user = filteredUsers[indexPath.row]!
}else{
user = self.usersArray[indexPath.row]!
}
cell.textLabel?.text = user["email"] as? String
cell.detailTextLabel?.text = user["name"] as? String
return cell
}
func filterContent(searchText: String){
self.filteredUsers = self.usersArray.filter({ user in
let userEmail = user!["email"] as? String
return(userEmail?.lowercased().contains(searchText.lowercased()))!
})
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//let vc = storyboard?.instantiateViewController(withIdentifier: "ConfirmationVC") as? PayViewController
//vc?.forField.text = filteredUsers[indexPath.row]!["email"] as! String
}
func setContents(searchText: String){
// searchT = searchText
}
as you can see at the very end of the tableviewcontroller, I have attempted to send information back using vc. is there any easier way of doing this?
Your attempt
let vc = storyboard?.instantiateViewController(withIdentifier: "ConfirmationVC") as? PayViewController
...fails because it makes a new, different instance of PayViewController - not the instance that contains this UsersTableViewController.
The PayViewController is this UsersTableViewController's parent. You might need to cast it to a PayViewController in order to call a method or set a property in it:
let vc = self.parent as? PayViewController
(Please note that it is unusual for one view controller to set another view controller's interface directly as you are attempting to do. You should provide PayViewController with a method that UsersTableViewController can call in good order.)
Although creating a delegate protocol and adding a delegate property to your tableViewController is a fine way to go, there's another way too.
Just add a property to your tableViewController that's a closure:
var updatedData: ((_ email: String, _ name: String)->Void)?
Your tableViewController can send information "up the chain" to an unknown parent view controller by simply calling
self.updatedData?(theEmail, theName)
In your parent view controller's viewDidLoad (or wherever you choose), have it do this:
tableViewController.updatedData =
{ [weak self] email, name in
// do your code here
}
So simple. There are various pros and cons to this approach vs. a formal protocol. I highly recommend you try both approaches and get very familiar with both so that over time you'll recognize when to use which approach. This approach is informal and is often more suitable for communicating "up the chain" within an app (vs. an SDK) especially where the parent view controller isn't likely to be swapped out for another. But it's also perfectly reasonable to say you always want to formalize everything via protocols. Just a little more code that way.
I actually use this informal approach a lot. I also wrap a bunch of these closure variables into a protocol that my view model would implement, just so that I can dependency inject a different view model when I am UI-testing a single view controller independently from my app. Anyhow, that's a different situation (viewModel to viewController communication, rather than your situation of child viewController to parent viewController communication).
I'm creating a quiz app with custom cells that include a label of questions and then an answer coming from a UISegmentedControl.
The values of the segmentedcontrols get changed when scrolling and this leads to an inaccurate score. I understand that this is due to UITableView reusing cells.
My tableview's datasource in my main vc is simply the labels for all my questions coming from a plist file.
The code for my custom tableviewcell class is
class QuestionsTableViewCell: UITableViewCell {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var selection: UISegmentedControl!
var question: String = "" {
didSet {
if (question != oldValue) {
questionLabel.text = question
}
}
}
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
}
//Just for testing
#IBAction func segmentChanged(_ sender: UISegmentedControl) {
print("value is ", sender.selectedSegmentIndex);
}
}
where the View is stored in an .XIB file.
And the code for my main vc is
class ViewController: UIViewController, UITableViewDataSource {
let questionsTableIdentifier = "QuestionsTableIdentifier"
#IBOutlet var tableView:UITableView!
var questionsArray = [String]();
var questionsCellArray = [QuestionsTableViewCell]();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let path = Bundle.main.path(forResource:
"Questions", ofType: "plist")
questionsArray = NSArray(contentsOfFile: path!) as! [String]
tableView.register(QuestionsTableViewCell.self,
forCellReuseIdentifier: questionsTableIdentifier)
let xib = UINib(nibName: "QuestionsTableViewCell", bundle: nil)
tableView.register(xib,
forCellReuseIdentifier: questionsTableIdentifier)
tableView.rowHeight = 108;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questionsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: questionsTableIdentifier, for: indexPath)
as! QuestionsTableViewCell
let rowData = questionsArray[indexPath.row]
cell.question = rowData
return cell
}
#IBAction func calculate(_ sender: UIButton) {
var score = 0
for cell in tableView.visibleCells as! [QuestionsTableViewCell] {
score += cell.selection.selectedSegmentIndex
}
let msg = "Score is, \(score)"
print(msg)
}
#IBAction func reset(_ sender: UIButton) {
for cell in tableView.visibleCells as! [QuestionsTableViewCell] {
cell.selection.selectedSegmentIndex = 0;
}
}
}
What I'd like to do is just keep track of all 'selection' changes of the Questions cells in an array, and then use that array in cellForRowAt. I'm just confused as to how i can dynamically keep track of changes from a view in another class. I'm new to Swift and would like to solve this is a proper MVC fashion. Thanks
Instead of a simple string array as data source create a class holding the text and the selected index
class Question {
let text : String
var answerIndex : Int
init(text : String, answerIndex : Int = 0) {
self.text = text
self.answerIndex = answerIndex
}
}
Declare questionArray as
var questions = [Question]()
Populate the array in viewDidLoad with
let url = Bundle.main.url(forResource: "Questions", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let questionsArray = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String]
questions = questionsArray.map {Question(text: $0)}
In the custom cell add a callback and call it in the segmentChanged method passing the selected index, the property question is not needed, the label is updated in cellForRow of the controller
class QuestionsTableViewCell: UITableViewCell {
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet weak var selection: UISegmentedControl!
var callback : ((Int) -> ())?
#IBAction func segmentChanged(_ sender: UISegmentedControl) {
print("value is ", sender.selectedSegmentIndex)
callback?(sender.selectedSegmentIndex)
}
}
In cellForRow add the callback and update the model in the closure
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: questionsTableIdentifier, for: indexPath) as! QuestionsTableViewCell
let question = questions[indexPath.row]
cell.questionLabel.text = question.text
cell.selection.selectedSegmentIndex = question.answerIndex
cell.callback = { index in
question.answerIndex = index
}
return cell
}
To reset the segmented controls in the cells set the property in the model to 0 and reload the table view
#IBAction func reset(_ sender: UIButton) {
questions.forEach { $0.answerIndex = 0 }
self.tableView.reloadData()
}
Now you could calculate the score directly from the model instead of the view.
Don't try to use cells to hold information. As the user scrolls through your table view, cells that scroll out of view will get recycled and their field settings will be lost. Also, newly dequeued cells will have the settings from the last time they were used.
You need to refactor your code to read/write information into a data model. Using an array of Structs as a data model is a reasonable way to go. (Or, as vadian suggests in his answer, and array of Class objects, so you get reference semantics.)
You have an IBAction segmentChanged() in your custom cell class. The next trick is to notify the view controller when the user changes the selection, and to update cells when you set them up in cellForRowAt.
I suggest defining a protocol QuestionsTableViewCellProtocol, and have the view controller conform to that protocol:
protocol QuestionsTableViewCellProtocol {
func userSelected(segmentIndex: Int, inCell cell: UITableViewCell)
}
}
Add a delegate property to your QuestionsTableViewCell class:
class QuestionsTableViewCell: UITableViewCell {
weak var delegate: QuestionsTableViewCellProtocol?
//The rest of your class goes here...
}
Update your cell's segmentChanged() method to invoke the delegate's userSelected(segmentIndex:inCell:) method.
In your view controller's cellForRowAt, set the cell's delegate to self.
func userSelected(segmentIndex: Int, inCellCell cell: UITableViewCell) {
let indexPath = tableView.indexPath(for: cell)
let row = indexPath.row
//The code below assumes that you have an array of structs, `dataModel`, that
//has a property selectedIndex that remembers which cell is selected.
//Adjust the code below to match your actual array that keeps track of your data.
dataModel[row].selectedIndex = segmentIndex
}
Then update cellforRowAt() to use the data model to set the segment index on the newly dequeued cell to the correct index.
Also update your calculate() function to look at the values in your dataModel to calculate the score, NOT the tableView.
That's a rough idea. I left some details out as "an exercise for the reader." See if you can figure out how to make that work.
I have a tableView which have one two cells.
first for section header having 3 buttons, acting as a check box,and
second cell with simple labels to populate the data.
Now what I want is to update the tableView's second cells data with a section header like shown in screenshot below. But I'm unable to get the clickable action for these buttons on the same header.
What I tried so far is:
first I used tapReconizer for all three of them, it was working but it was not changing the image of the button (which is imp, as through image it is acting like a checkbox)
then I made the action outlet for all three now they are working as in but I'm unable to update data from the cell's custom class, below is the code
class SavedCallHeader : UITableViewCell{
var checkBox_PlannedisOn:Bool = false
var checkBox_BothisOn:Bool = true
var checkBox_unPlannedisOn:Bool = false
let defaults = UserDefaults.standard
#IBOutlet weak var PlannedBoxBtn: UIButton!
#IBOutlet weak var BothBoxBtn: UIButton!
#IBOutlet weak var unPlannedBoxBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
}
#IBAction func PlannedCheckBox(_ sender: UIButton) {
if checkBox_PlannedisOn == false {
self.PlannedBoxBtn.setImage(UIImage(named: "Checked Checkbox-26.png"), for: UIControlState.normal)
checkBox_PlannedisOn = true
print("i'm finally here proper click!")
// self.fetchData() // wont' work here as it is in the main VC Class
// tableView.reloadData() // won't work here as well
}else {
self.PlannedBoxBtn.setImage(UIImage(named: "Unchecked Checkbox-26.png"), for: UIControlState.normal)
print("i'm finally heress proper click!")
checkBox_PlannedisOn = false
}
}
I want to update and refresh data on every time the user select/deSelect the checkBox. Below is my main code:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let identifierHeader:String = "SavedCallHeader"
let headerCell = tableView.dequeueReusableCell(withIdentifier: identifierHeader) as! SavedCallHeader
/* let tapPlanned = UITapGestureRecognizer(target: self, action: #selector(self.respondToSwipeGestureP))
let tapBoth = UITapGestureRecognizer(target: self, action: #selector(self.respondToSwipeGestureB))
let tapUnPlanned = UITapGestureRecognizer(target: self, action: #selector(self.respondToSwipeGestureU))
headerCell.PlannedBoxBtn.addGestureRecognizer(tapPlanned)
headerCell.BothBoxBtn.addGestureRecognizer(tapBoth)
headerCell.unPlannedBoxBtn.addGestureRecognizer(tapUnPlanned)
*/
return headerCell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier:String = "savedcall_cell"
let cell:SavedCalls_Cell = self.tableView.dequeueReusableCell(withIdentifier:identifier ) as! SavedCalls_Cell!
if(drname.count > 0){
//Fetching data from table view and then reload
}
Creating callBack like this in your cell class
var callBackForReload : ((Bool) -> ())?
#IBAction func PlannedCheckBox(_ sender: UIButton) {
// when you call this call back it will excute in where you acces it.
// I pass bool value for examble. you will pass whtever datatype you want
self.callBackForReload!(true)
}
The below code execute after CallBack code executed in your cell class
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let identifierHeader:String = "SavedCallHeader"
let headerCell = tableView.dequeueReusableCell(withIdentifier: identifierHeader) as! SavedCallHeader
headerCell.callBackForReload = { [weak self] (isCalled) -> Void in
//This will call when the call back code excuted in your cell class
// in The isCalled variable you will get the value from cell class
// You will reload your changed value here
}
return headerCell
}
You have to do below things,
Instead of UITableViewCell, you have to take Button Outlets in ViewController.
When User clicked on any cell you can get on which button and cell user clicked. Ref
Now reload that cell/section as user clicked. Ref
I'm a newbie learning iOS and Swift so apologies ahead of time. Currently I'm trying to setup a tableView within a viewController and display data in the cells in a portion of the screen. My current problem seems to be in reloading the tableView data after the Alamofire HTTP request in viewDidLoad() is called for numberOfRowsInSection(). Here's the code:
import UIKit
import Alamofire
import SwiftyJSON
class CourseDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var titleLabel: UILabel?
#IBOutlet weak var creditsLabel: UILabel?
#IBOutlet weak var descriptionLabel: UILabel?
#IBOutlet weak var tableView: UITableView!
var detailCourse: Course? {
didSet {
configureView()
}
}
var course: Course!
func configureView() {
self.title = detailCourse?.abbr
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SectionCell")
tableView.delegate = self
tableView.dataSource = self
if let theCourse: Course = self.detailCourse as Course! {
var abbr: String = theCourse.abbr!
APIService.getCourseByAbbr(abbr) { (data) -> Void in
self.course = Course(courseJSON: data)
// Set labels
self.titleLabel?.text = self.course.title!
self.descriptionLabel?.text = self.course.description!
if let creditsArray = self.course.credits {
let minimumCredit = creditsArray[0] as Int
self.creditsLabel?.text = String(minimumCredit)
}
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return course.sections.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("SectionCell", forIndexPath: indexPath) as! SectionTableViewCell
let sectionCell = course.sections[indexPath.row]
cell.termLabel?.text = sectionCell.term
cell.timeLabel?.text = sectionCell.startTime
cell.instructorLabel?.text = sectionCell.instructor
return cell
}
}
When I run, I get the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I believe that the reason may be that I set up the tableView within the viewController incorrectly.
For the full project, here is a link to the repo: https://github.com/classmere/app/tree/develop
The problem is that you're trying to unwrap an optional whose value is nil. When you declare the course property, since its an optional, its initial value is nil. Usually, optionals are declared with ? and the compiler will prevent you from accessing the underlying value without checking if the value is still nil. In this case however, you've made the course property an expected optional:
var course: Course!
This is like saying "I know that course will always have a value and will never be nil". We don't know that however, since its value is nil until the Alamofire callback successfully completes.
To fix this problem, start by making course a standard optional:
var course: Course?
Now Xcode will complain that you're accessing course without unwrapping it, since your declaration of course no longer unwraps it.
Fix this by forcibly unwrapping everything in the Alamofire callback:
APIService.getCourseByAbbr(abbr) { (data) -> Void in
println("APIService()")
self.course = Course(courseJSON: data)
// Notice we can access self.course using ! since just assigned it above
self.titleLabel?.text = self.course!.title!
self.descriptionLabel?.text = self.course!.description!
if let creditsArray = self.course!.credits {
let minimumCredit = creditsArray[0] as Int
self.creditsLabel?.text = String(minimumCredit)
}
self.tableView.reloadData()
}
Then in cellForRowAtIndexPath, we will use optional chaining to ensure we only access course's properties if they exist:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("SectionCell", forIndexPath: indexPath) as! SectionTableViewCell
if let section = course?.sections[indexPath.row] {
cell.termLabel?.text = section.term
cell.timeLabel?.text = section.startTime
cell.instructorLabel?.text = section.instructor
}
return cell
}
Finally in numberOfRowsForSection make sure to get the actual number of sections instead of always returning 50. We'll use the nil-coalescing operator to return 0 if course is nil:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return course?.sections.count ?? 0
}
That should fix your problem!