Swift make wishlist feature - ios

so I want to make this simple wishlist feature for when the user tapped the "heart" button it will add that data from view to wishlist view. just like this :
so when the user tapped that heart button, that movie will show in this wishlist view like this :
now, my question is how do I notify my wishlistVc so that it knows there's a new "wishlist" that the user tapped from the movie list. I have an idea that I should use a delegate, but still, I can't figure out how to implement a delegate in this case.
and I use "var movieList" to store all the data in HomeVc, and my idea is when the user tapped that heart button in tableview, that data that user tapped with will move into my "let wishlist", so i can populate it on my wishlistVC ( but I don't know how to do this so I need help)
so far this is my code :
class DefaultTableViewCell: UITableViewCell {
#IBOutlet weak var moviePosterImage: UIImageView!
#IBOutlet weak var movieTitleLabel: UILabel!
#IBOutlet weak var wishlistButton: UIButton!
var indexPath: IndexPath!
var delegate: DefaultTableViewDelegate?
var wishlistFlag:Bool = false
override func layoutSubviews() {
super.layoutSubviews()
wishlistButton.titleLabel?.text = ""
wishlistButton.addTarget(self, action: #selector(wishlistTapped(_:)), for: .valueChanged)
}
#IBAction func wishlistTapped(_ sender: UIButton) {
wishlistFlag = !wishlistFlag
delegate?.wishlistTrigger(row: indexPath.row)
if wishlistFlag == true {
wishlistButton.setImage(UIImage(named: "heart_fill"), for: .normal)
}else if wishlistFlag == false {
wishlistButton.setImage(UIImage(named: "heart"), for: .normal)
}
}
}
HomeVc (the vc that shows the movie list):
var movieList : [Movie] = []
extension HomeVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movieList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = movieList[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultTableViewCell", for: indexPath) as! DefaultTableViewCell
cell.indexPath = indexPath
cell.movieTitleLabel.text = data.title
cell.moviePosterImage.sd_setImage(with: data.imageUrl)
cell.delegate = self
return cell
}
}
protocol DefaultTableViewDelegate {
func wishlistTrigger(row: Int)
}
this is my wishlistVc:
let wishlist : [Movie] = []
extension WishlistVc: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wishlist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = wishlist[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultTableViewCell", for: indexPath) as! DefaultTableViewCell
cell.movieTitleLabel.text = data.title
cell.moviePosterImage.sd_setImage(with: data.imageUrl)
cell.wishlistButton.titleLabel?.text = ""
cell.indexPath = indexPath
return cell
}
}
I've been stuck for 2 whole days now I still don't know how to figure this out. I appreciate anyone that can help me. Thanks

Implement func like:
func wishlistTrigger(row: Int) {
self.myWishlistedItem.append(self.movieList[row]) //Add that wishlisted item in array
self.tableView.reloadData() //Now reload Table
}

Related

how to activate slider IBAction from cell in TableViewCell? [duplicate]

This question already has an answer here:
Swift Using a UISlider in a UITableViewCell the right way?
(1 answer)
Closed 2 years ago.
My program is creating slider in dynamic cell. I can't just create IBAction using ctrl+"drag and drop" on slider because it is in cell, not in viewController. How can I create this IBAction in ViewController?
class SecondViewController: UIViewController {
var gradesNumber: Int?
var gradeArray: [Grade] = []
#IBOutlet weak var topLabel: UILabel!
#IBOutlet weak var gradesTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
gradesTableView.dataSource = self
for i in 1...gradesNumber! {
gradeArray.append(Grade(sliderValue: 5, title: "Grade \(i)", grade: "5"))
}
gradesTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "ReusableCell")
}
#IBAction func calculateButton(_ sender: UIButton) {
var avg = 0.0
for i in gradeArray {
avg += Double(i.grade)!
}
topLabel.text = "Avg: \(avg/Double(gradesNumber!))"
}
}
extension SecondViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gradesNumber ?? 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! TableViewCell
cell.gradeSlider.tag = indexPath.row
cell.gradeSlider.setValue(5, animated: true)
let slider: Grade = gradeArray[indexPath.row]
cell.gradeValue.text = slider.grade
cell.gradeNumber.text = slider.title
return cell
}
}
As Lucas says in his comment, you can create a custom subclass of UITableViewCell and attach the action to the cell class. Then you'd forward the message from the cell to the owning table view. (You'd probably need a delegate property on the cell class so you know who to forward the action to.)
Alternately, you could configure the IBAction in your cellForRowAt method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! TableViewCell
//other config code
//Make sure the slider doesn't already have the action attached.
if cell.gradeSlider.actions(forTarget: nil, forControlEvent: .valueChanged) == nil {
cell.gradeSlider.addTarget(self, action: #selector(actionSelector(:)), controlEvents: .valueChanged]
}
return cell
}

Table view cell elements not able to click and get data

I have one table view and inside that i placed one main view. And inside that main view i placed one button.And when ever use click on my cell button. I need to get the cell title label.This is what i need. But i tried following below code. Not sure what i am missing out. It not at all calling my cell.add target line.
Code in cell for row at index:
cell.cellBtn.tag = indexPath.row
cell.cellBtn.addTarget(self, action:#selector(self.buttonPressed(_:)), for:.touchUpInside)
#objc func buttonPressed(_ sender: AnyObject) {
print("cell tap")
let button = sender as? UIButton
let cell = button?.superview?.superview as? UITableViewCell
let indexPath = tableView.indexPath(for: cell!)
let currentCell = tableView.cellForRow(at: indexPath!)! as! KMTrainingTableViewCell
print(indexPath?.row)
print(currentCell.cellTitleLabel.text)
}
I even added a breakpoint, still it not at calling my cell.addTarget line
Tried with closure too. In cell for row at index:
cell.tapCallback = {
print(indexPath.row)
}
In my table view cell:
var tapCallback: (() -> Void)?
#IBAction func CellBtndidTap(_ sender: Any) {
print("Right button is tapped")
tapCallback?()
}
Here that print statement is getting print in console.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var list = [String]()
#IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
cell.saveButton.tag = indexPath.row
//cell.saveButton.accessibilityIdentifier = "some unique identifier"
cell.tapCallback = { tag in
print(tag)
}
return cell
}
}
class MyTableViewCell: UITableViewCell {
// MARK: - IBOutlets
#IBOutlet weak var saveButton: UIButton!
// MARK: - IBActions
#IBAction func saveTapped(_ sender: UIButton) {
tapCallback?(sender.tag)
}
// MARK: - Actions
var tapCallback: ((Int) -> Void)?
}
Actually this is not a good programming practice to add the button (which contains in table view cell) target action in view controller. We should follow the protocol oriented approach for it. Please try to under stand the concept.
/*This is my cell Delegate*/
protocol InfoCellDelegate {
func showItem(item:String)
}
/*This is my cell class*/
class InfoCell: UITableViewCell {
//make weak reference to avoid the Retain Cycle
fileprivate weak var delegate: InfoCellDelegate?
//Outlet for views
#IBOutlet var showButton: UIButton?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//This is the public binding function which will bind the data & delegate to cell
func bind(with: DataModel?, delegate: InfoCellDelegate?, indexPath: IndexPath) {
//Now the bind the cell with data here
//.....
//Assign the delegate
self.delegate = delegate
}
//Button action
#IBAction func rowSelected(sender: UIButton) {
self.delegate?.showItem(item: "This is coming from cell")
}
}
/*Now in your ViewController you need to just confirm the InfoCellDelegate & call the bind function*/
class ListViewController: UIViewController {
//Views initialisation & other initial process
}
//Table view Delegate & Data source
extension ListViewController: UITableViewDataSource, UITableViewDelegate {
/**
Configure the table views
*/
func configureTable() {
//for item table
self.listTable.register(UINib.init(nibName: "\(InfoCell.classForCoder())", bundle: nil), forCellReuseIdentifier: "\(InfoCell.classForCoder())")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
cell.bind(with: DataModel, delegate: self, indexPath: indexPath)
return cell
}
}
extension ListViewController: InfoCellDelegate {
func showItem(item) {
print(item)
}
}

How to create controls dynamically and aligned dynamically in swift 4?

I am working on the iOS application with Swift 4. In that project I have requirement like, I have to create controls dynamically along with the proper alignment.
For example, I have a button when I click on that button I am hitting the service from that I am getting json data which contains 4 objects. Based on that I have to create controls dynamically and dynamic alignment also should do. I tried lot of examples and tutorials. I didn’t find any solution.
You can use UITableView for that and here is example:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableview: UITableView!
var nameArr :[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func four_btn(_ sender: Any) {
nameArr.removeAll()
let nameData = ["First Name","Middle Name","Last Name","DOB"]
nameArr += nameData
tableview.reloadData()
}
#IBAction func eight_btn(_ sender: Any) {
nameArr.removeAll()
let nameData = ["Salutation","First Name","Middle Name","Last Name","DOB","Gender","Mobile","Email"]
nameArr += nameData
tableview.reloadData()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableviewCells
cell.nameLabel.text = nameArr[indexPath.row]
return cell
}
}
class tableviewCells : UITableViewCell{
#IBOutlet weak var nameLabel: UILabel!
}
You can use UITableView for the same
Your scenario is like, it may possible that one user having 5 records however another may have 10 or 12 records means you've to work dynamically
if there are 2 buttons which calls 2 different APIs then just manage 2 different array like this
var arr1 = NSArray()
var arr2 = NSArray()
var isAPI1Called = Bool()
save response of both apis in different array
then just manage flag on button tap and in suitable view like this
#IBAction func btn1(_ sender: Any) {
isAPI1Called = true
self.API1Called()
}
#IBAction func btn2(_ sender: Any) {
isAPI1Called = false
self.API1Called()
}
Now use flag in UITableview Delegate like this
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isAPI1Called
{
return arr1.count
}
else
{
return arr2.count
}
}
Load UITableviewCell as per your requirement if UI changed
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if isAPI1Called
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! UITableviewCell
//Do your required stuff here
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! UITableviewCell
//Do your required stuff here
return cell
}
}
Hope it will help you
Comment if not get any point

How to have each UITableViewOption have its own data

I am trying to have each choice in my UITableView to have its own unique set of data. For example, in my table view I have a list of states, then when I click on a state, I want each state to have a list of cities that correspond specifically to it. I have attached my code below, the code is strictly for the UITableView only.
I'm new to Xcode/Swift.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let textCellIdentifier = "TextCell"
var states = ["Illinois", "Indiana", "Kentucky", "Michigan", "Ohio", "Pennsylvania", "Wisconsin"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return states.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath)
let row = indexPath.row
cell.textLabel?.text = states[row]
return cell
}
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let row = indexPath.row
print(states[row])
}
You can construct array model like this
struct MainItem {
var name:String
var cities:[String]
init(name:String,cities:[String]) {
self.name = name
self.cities = cities
}
}
//
let item1 = MainItem(name:"Illinois",cities:["city1","city2"])
let item2 = MainItem(name:"Indiana",cities:["city3","city4"])
var states = [item1,item2]
//
in cellForRowAt
cell.textLabel?.text = states[row].name
//
in didSelectRowAtIndexPath
let cities = states[row].cities
I recently did this by creating separate classes for each of the delegates I wanted to have. Move all of the table functions into a new class and create an instance of the class in your new controller. In the view did load function set the delegate for the first table. Whenever you switch tables with a button or whatever, do nextTable.delegate = xxxx.
View controller code:
let eventLogTableController = EventLogTableController()
let missedEventLogController = MissedEventTableController()
#IBOutlet weak var emptyTableLabel: UILabel!
#IBOutlet weak var missedEventLog: UITableView!
override func viewDidLoad() {
self.eventLog.delegate = eventLogTableController

Save textField value to cell textLabel (name) [SWIFT]

I'm going to do something like this https://i.stack.imgur.com/jAGsk.png
So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file
#IBOutlet weak var inputScore: UITextField!
public func configure(text: Int?, placeholder: String) {
inputScore.text = String(text!)
inputScore.placeholder = placeholder
inputScore.accessibilityValue = String(text!)
inputScore.accessibilityLabel = placeholder
}
And here is code from the VC file
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
cell.textLabel?.text = usersIn[indexPath.row]
cell.configure(text: 100, placeholder: "Score")
return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usersIn.count
}
So how to save it to the user's name?
Use DidSelectRowAtIndexPath method to get cell textLable text in textField.
Below Sample Code for That:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet var btnOK: UIButton!
#IBOutlet var txtValue: UITextField!
#IBOutlet var tblData: UITableView!
let arrResult = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
tblData.dataSource = self
tblData.delegate = self
btnOK.tag = 57775
btnOK.addTarget(self, action: #selector(applyEdit(sender:)), for: .touchUpInside)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrResult.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = arrResult[indexPath.row] as? String ?? ""
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
btnOK.tag = indexPath.row
let cell: UITableViewCell = tableView.cellForRow(at: indexPath)!
txtValue.text = cell.textLabel?.text
setTitle()
}
func setTitle() {
if btnOK.tag == 57775 {
btnOK.setTitle("Add", for: .normal)
}else{
btnOK.setTitle("Update", for: .normal)
}
}
func applyEdit(sender: UIButton) {
if sender.tag == 57775 {
arrResult.add(txtValue.text ?? "")
}else{
arrResult.removeObject(at: sender.tag)
arrResult.insert(txtValue.text ?? "", at: sender.tag)
sender.tag = 57775
setTitle()
}
txtValue.text = ""
tblData.reloadData()
}
}
output:
You have to create a data model for your users:
class User: NSObject {
var points = 0
}
And then create an array of users in your view controller:
var users = [User]()
That way, you can do something like this
var user = users[indexPath.row]
user.points = 100
print(user.points) // 100
You can then display your users' points in your table view. You can also assign a tag to your text fields equal to the indexPath.row so that you can easily work with them.
In top of use user model provided by #Cesare we need to modified the cellForRowAtIndexPath method and your cell's implementation, adding a closure for data change event, and using it
#IBOutlet weak var inputScore: UITextField!
fileprivate var fnDataWasUpdated : (Int?) -> Void = {_ in} //closure for data change notification
public func configure(text: Int?, placeholder: String,_ fnListener: #escaping (Int?) -> Void) {
inputScore.text = String(text!)
inputScore.placeholder = placeholder
inputScore.accessibilityValue = String(text!)
inputScore.accessibilityLabel = placeholder
//added delegate implementation for UITextField
inputScore.delegate = self
self.fnDataWasUpdated = fnListener
}
also is needed that your cell adopts UITextFieldDelegate protocol
extension InputScoreTableViewCell : UITextFieldDelegate
{
func textFieldDidEndEditing(_ textField: UITextField)
{
if let intValue = Int(textField.text)
{
self.fnDataWasUpdated(intValue)
}
}
}
Finally we use the new closure in your cell
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
let currUser = self.users[indexPath.row]
cell.configure(text: currUser.points, placeholder: "Score",{ (newIntValue) in
currUser.points = newIntValue
})
return cell
}
This code was not tested but I had been using the main concept in several projects, so if you have any kind of problems please let me know
I hope this helps you

Resources