Checkout shopping cart UICollectionViewCell - ios

I have a shopping cart check out flow using a UICollectionView with full page UICollectionViewCells. When the add button is pressed, the remove button is then visible and vice versa. For some reason when add and remove are repeatedly pressed it disrupts the other cells. It will show remove button on another cell when the add button on that cell was never even pressed. I am not sure what's wrong with my logic.
protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
}
class PostCell: UICollectionViewCell {
var currentPrice: Float = 0
var delegate: PostCellDelegate?
func set(name: String, brand: String, price: String, image: String){
nameLabel.text = name
brandLabel.text = brand
priceLabel.text = "$\(price)"
photoImageView.loadImage(urlString: image)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
self.contentView.addSubview(containerView)
setupCellConstraints()
}
#objc func addButtonTapped(sender: UIButton){
self.delegate?.addTapped(cell: self)
sender.isHidden = true
}
#objc func subButtonTapped(sender: UIButton){
self.delegate?.removeButtonTapped(cell: self)
sender.isHidden = true
}
}
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var totalPrice = Float()
private var hiddenRows = Set<Int>()
var finalList = [Item]()
#objc func addTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else {return}
hiddenRows.insert(indexPath.row)
cell.removeButton.isHidden = false
let item = itemsArr[indexPath.row]
finalList.append(item)
collectionView?.reloadData()
totalPrice += Float(item.price) ?? 0
}
#objc func removeButtonTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else {return}
hiddenRows.insert(indexPath.row)
cell.myButton.isHidden = false
let item = itemsArr[indexPath.row]
finalList.removeAll{ $0.name == item.name}
totalPrice -= Float(item.price) ?? 0
}
extension CollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
cell.delegate = self
let item = itemsArr[indexPath.row]
let page = itemsArr[indexPath.item]
cell.set(name: item.name, brand: item.brand, price: item.price, image: item.image_url)
if hiddenRows.contains(indexPath.row) {
cell.myButton.isHidden = true
cell.removeButton.isHidden = false
}else{
cell.removeButton.isHidden = true
cell.myButton.isHidden = false
}
return cell
}

Cells are reused you need to restore to default here in cellForItemAt
// restore default look here ( hide / show what you need )
if hiddenRows.contains(indexPath.row) {
cell.myButton.isHidden = true
cell.removeButton.isHidden = false
}else{
cell.removeButton.isHidden = true
cell.myButton.isHidden = false
}

It was because in removeButtonTapped I had hiddenRows.insert(indexPath.row) instead of hiddenRows.remove(indexPath.row). I don't know how I missed that.

Related

UITableView not updating data

I have trying for sometime to make the "reloadData()" work but it is not working. I've even tried "DispatchQueue.main.async{self.tableView.reloadData()}"
Below is the code
import UIKit
import QuartzCore
import GameKit
enum Tags: Int {
case levelLabel = 100
case background = 101
case highScoreLabel = 102
case star1 = 201
case star2 = 202
case star3 = 203
}
let LightBlue = UIColor.systemBlue
let Green = UIColor.systemRed
let Purple = UIColor.systemPurple
let Pink = UIColor.systemPink
let Orange = UIColor.systemOrange
let OneStarScore = 5
let TwoStarScore = 10
let ThreeStarScore = 15
let NumLevels = 11
class HomeViewController: UIViewController, UITableViewDataSource,
UITableViewDelegate, GKGameCenterControllerDelegate {
#IBOutlet weak var tableView: UITableView!
var highScores: [Int] = [Int]()
var unlockedLevels = 0
let colors = [LightBlue, Green, Purple, Pink, Orange]
var tutorialPageVC: PageDataSourceViewController?
var gameVC: GameViewController?
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
tableView.separatorColor = UIColor.systemBackground
} else {
// Fallback on earlier versions
}
let storyboard = self.storyboard
tutorialPageVC = storyboard?.instantiateViewController(withIdentifier: "PageDataSourceVC")
as? PageDataSourceViewController
gameVC = storyboard?.instantiateViewController(withIdentifier: "GameViewController")
as? GameViewController
// Trying to fix UITableView
/// Put code here
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
let defaults = UserDefaults.standard
if let scoresArray = defaults.array(forKey: "highScores") {
highScores = scoresArray as! [Int]
unlockedLevels = highScores.count - 1 // Subtract one for tutorial
if highScores[unlockedLevels] >= 5 {
unlockedLevels += 1 // Unlock additional level if last high score is greater than 5
}
}
}
// MARK: - TableView data source methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumLevels
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LevelCell", for: indexPath)
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let view = cell.viewWithTag(Tags.background.rawValue) as UIView?
let levelLabel = cell.viewWithTag(Tags.levelLabel.rawValue) as! UILabel
let scoreLabel = cell.viewWithTag(Tags.highScoreLabel.rawValue) as! UILabel
let star1 = cell.viewWithTag(Tags.star1.rawValue) as! UIImageView
let star2 = cell.viewWithTag(Tags.star2.rawValue) as! UIImageView
let star3 = cell.viewWithTag(Tags.star3.rawValue) as! UIImageView
view?.layer.borderColor = colors[indexPath.row % 5].cgColor
view?.layer.borderWidth = 6.0
if indexPath.row == 0 {
// Tutorial Level
view?.alpha = 1.0
levelLabel.text = "Tutorial"
star1.isHidden = true
star2.isHidden = true
star3.isHidden = true
scoreLabel.text = ""
} else if indexPath.row + 1 <= highScores.count {
// Levels that have been played
view?.alpha = 1.0
levelLabel.text = "Level \(indexPath.row)"
star1.isHidden = false
star2.isHidden = false
star3.isHidden = false
formatStars(highScores[indexPath.row], stars: [star1, star2, star3])
scoreLabel.text = "High Score: \(highScores[indexPath.row])"
} else {
// Levels that have NOT been played
view?.alpha = indexPath.row > unlockedLevels ? 0.5 : 1.0
levelLabel.text = "Level \(indexPath.row)"
star1.isHidden = true
star2.isHidden = true
star3.isHidden = true
scoreLabel.text = ""
}
return cell
}
/// Display stars for each level on homepage
func formatStars(_ score: Int, stars: [UIImageView]) {
switch score {
case 0..<OneStarScore:
stars[0].image = UIImage(named: "star-empty")
stars[1].image = UIImage(named: "star-empty")
stars[2].image = UIImage(named: "star-empty")
case OneStarScore..<TwoStarScore:
stars[0].image = UIImage(named: "star")
stars[1].image = UIImage(named: "star-empty")
stars[2].image = UIImage(named: "star-empty")
case TwoStarScore..<ThreeStarScore:
stars[0].image = UIImage(named: "star")
stars[1].image = UIImage(named: "star")
stars[2].image = UIImage(named: "star-empty")
default:
stars[0].image = UIImage(named: "star")
stars[1].image = UIImage(named: "star")
stars[2].image = UIImage(named: "star")
}
}
// MARK: - TableView delegate methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
self.present(tutorialPageVC!, animated: true, completion: nil)
} else if indexPath.row <= unlockedLevels {
gameVC!.level = indexPath.row
self.present(gameVC!, animated: true, completion: nil)
// performSegueWithIdentifier("LevelSegue", sender: self)
}
}
Maybe the connection between the UITableView and the delegate and data source are not set.
You could do this in the storyboard by ctrl+dragging from the table view to the view controller and setting the delegate and data source outlets.
Or you can do so in code, e.g. in viewDidLoad:
self.tableView.dataSource = self
self.tableView.delegate = self
You need to set dataSource and delegate to self
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.datasource = self
}
And Assign values directly like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LevelCell", for: indexPath) as? LevelCell
cell?.star1.isHidden = true
}

Saved object array not showing up in new ViewController

Every time my add button is pressed I am attempting to append that specific item into an array of Item. It prints in the console for each new cell, however when I push to a new ViewController, which will be a summary of all the items added, it does not print the items. Only an empty array is printed.
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var finalList = [Item]()
#objc func addTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else {return}
hiddenRows.insert(indexPath.row)
cell.removeButton.isHidden = false
let item = itemsArr[indexPath.row]
finalList.append(item)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
cell.delegate = self
let item = itemsArr[indexPath.row]
cell.set(name: item.name, brand: item.brand, price: item.price)
print(finalList)
return cell
}
#objc private func handleNext() {
let nextIndex = min(pageControl.currentPage + 1, itemsArr.count - 1)
let indexPath = IndexPath(item: nextIndex, section: 0)
if pageControl.currentPage == 4{
let checkoutView = FinishViewController()
self.navigationController?.pushViewController(checkoutView, animated: true)
checkoutView.modalPresentationStyle = .overCurrentContext
present(checkoutView, animated: true)
print("last item")
}else {
print("not last")
}
pageControl.currentPage = nextIndex
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
lazy var pageControl: UIPageControl = {
let pc = UIPageControl()
pc.currentPage = 0
pc.numberOfPages = 4
pc.currentPageIndicatorTintColor = .red
pc.pageIndicatorTintColor = UIColor(red: 249/255, green: 207/255, blue: 224/255, alpha: 1)
return pc
}()
class FinishViewController: UIViewController {
let cV = CollectionViewController()
override func viewDidLoad() {
print(cV.finalList)
super.viewDidLoad()
view.backgroundColor = .red
}
The issue is that in the FinishViewController you are initializing a new instance of CollectionViewController, so the property has the default empty array value.
You need to pass in the array to the FinishViewController when you present or segue to it.
In FinishViewController add the following:
var finalList = [Item]()
And in handleNext make sure you set finalList correctly:
let checkoutView = FinishViewController()
checkoutView.finalList = self.finalList
#objc func addTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else
{return}
hiddenRows.insert(indexPath.row)
cell.removeButton.isHidden = false
let item = itemsArr[indexPath.row]
finalList.append(item)
collectionView?.reloadData() <---- add this
}

Detect last cell in full page UICell UICollectionView

I have a checkout flow using a UICollectionViewController and a full page UICell. After the last cell(the last item) is displayed I want to add a summary page of all the items that have been added to the shopping cart along with a total price. I tried to check if the last item = itemsArray.count - 1 however it keeps printing "last item" in the cell before last. Also in the last cell, it prints "not last".
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
var totalPrice = Float()
private var hiddenRows = Set<Int>()
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
cell.finalLabel.text = String(totalPrice)
cell.delegate = self
let item = itemsArr[indexPath.row]
cell.set(name: item.name, brand: item.brand, price: item.price)
if indexPath.row == itemsArr.count - 1 {
print("last item")
}else {
print("not last")
}
if hiddenRows.contains(indexPath.row) {
cell.myButton.isHidden = true
cell.removeButton.isHidden = false
}else{
cell.removeButton.isHidden = true
cell.myButton.isHidden = false
}
cell.finalLabel.text = String(totalPrice)
return cell
}
#objc func addTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else {return}
hiddenRows.insert(indexPath.row)
cell.removeButton.isHidden = false
let item = itemsArr[indexPath.row]
print(item.price)
totalPrice += Float(item.price) ?? 0
cell.finalLabel.text = String(totalPrice)
}
#objc func removeButtonTapped(cell: PostCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else {return}
hiddenRows.insert(indexPath.row)
cell.myButton.isHidden = false
let item = itemsArr[indexPath.row]
totalPrice -= Float(item.price) ?? 0
cell.finalLabel.text = String(totalPrice)
}
}
protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
func didPressButton(_ tag: Int)
}
class PostCell: UICollectionViewCell {
var delegate: PostCellDelegate?
func set(name: String, brand: String, price: String){
nameLabel.text = name
brandLabel.text = brand
priceLabel.text = price
}
override init(frame: CGRect) {
super.init(frame: frame)
self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
setupCellConstraints()
}
#objc func buttonPressed(_ sender: UIButton) {
delegate?.didPressButton(sender.tag)
}
#objc func addButtonTapped(sender: UIButton){
self.delegate?.addTapped(cell: self)
sender.isHidden = true
}
#objc func subButtonTapped(sender: UIButton){
self.delegate?.removeButtonTapped(cell: self)
sender.isHidden = true
}
}

Pass IndexPath row value to delegate function instead of Sender.tag to delete Image item CollectionView Swift

I am using collectionView to display photos and delegate functions to view custom alert.
On photos I have cross mark which is for delete photo. My delegate functions and display items all working fine.
But I am getting Issue when I have to delete photo from server. Because I need to pass exact image ID to web service to remove it from server. If I use cell.tag thing it gives me row value which is 1 but actual imgID is 40992. How can I pass this value to my delete delegate function?
Structure:
cell items display --tap gesture call removeImage func --- custom alert -- on Delete button -- didDeleteButtonClicked called.
Main Value which I need in cellForItem:
let imgId = AppData?.imageList?[indexPath.row].projectUnitImageId
PhotoViewController:
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath) as! PhotoCollectionViewCell
if(indexPath.row < (AppData?.imageList?.count ?? 0)){
cell.imageView.isHidden = false
cell.closeIcon.isHidden = false
cell.addIcon.isHidden = true
let dic = AppData?.imageList?[indexPath.row].url ?? " "
cell.imageView.image = UIImage(url: URL(string: dic))
let imgId = AppData?.imageList?[indexPath.row].projectUnitImageId
print(imgId)
cell.closeIcon.isUserInteractionEnabled = true
cell.closeIcon.tag = imgId ?? 0
deleteAlertView.delegate = self
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(removeImage(_:)))
cell.closeIcon.addGestureRecognizer(tapGestureRecognizer)
} else {
cell.imageView.isHidden = true
cell.closeIcon.isHidden = true
cell.addIcon.isHidden = false
}
return cell
}
#objc func removeImage(_ sender: AnyObject){
print(imgId)
let fotoXib = Bundle.main.loadNibNamed("FotoDeleteAlert", owner: self, options: nil)
let alertView = fotoXib?.first as! FotoDeleteAlert
alertView.delegate = self
self.view.addSubview(alertView)
}
//MARK: - Delegate Function
extension PhotoCollectionViewController: handleDeleteAction {
func didDeleteButtonClicked(_ sender: UIButton) {
print("delegate")
let row = sender.tag
print(row)
// I have to call my delete webServices here and have to pass imgId
deleteWebservices(imgId)
}
}
FotoAlert Xib custom alert:
protocol handleDeleteAction {
func didDeleteButtonClicked(_: UIButton)
}
#IBDesignable class FotoDeleteAlert: UIView {
var delegate: handleDeleteAction?
#IBOutlet weak var deleteBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
layoutIfNeeded()
deleteBtn.addTarget(self, action: #selector(didDelete(_:)), for: .touchUpInside)
}
#IBAction func didCancel(_ sender: Any) {
removeFromSuperview()
}
#IBAction func didDelete(_ sender: UIButton) {
self.delegate?.didDeleteButtonClicked(sender)
removeFromSuperview()
}
}
TL;DR;
You set tag of cell.closeIcon but then you use tag of FotoDeleteAlert button.
To fix that you need to add
class FotoDeleteAlert: ... {
...
func setButtonTag(imageId: Int) {
button.tag = imageId
}
}
#objc func removeImage(_ sender: UIView){
print(imgId)
let fotoXib = Bundle.main.loadNibNamed("FotoDeleteAlert", owner: self, options: nil)
let alertView = fotoXib?.first as! FotoDeleteAlert
alertView.setButtonTag(imageId: sender.tag
alertView.delegate = self
self.view.addSubview(alertView)
}
extension PhotoCollectionViewController: handleDeleteAction {
func didDeleteButtonClicked(_ sender: UIButton) {
print("delegate")
let imgId = sender.tag
// I have to call my delete webServices here and have to pass imgId
deleteWebservices(imgId)
}
}
Now let's cleanup your spaghetti code
Most of your collectionView(_:, cellForItemAt: ) can be moved into PhotoCollectionViewCell.
I wouldn't send id via tag, instead you can create own delegate
Finally I would rewrite it into something like:
class Controller {
func displayAlert(for info: PhotoInfo) {
// I bet this code is invalid (view isn't correctly aligned
let fotoXib = Bundle.main.loadNibNamed("FotoDeleteAlert", owner: self, options: nil)
let alertView = fotoXib?.first as! FotoDeleteAlert
alertView.delegate = self
self.view.addSubview(alertView)
}
}
extension Controller: UICollectionViewDelegate {
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: cellName, for: indexPath
) as! PhotoCollectionViewCell
let imgInfo: PhotoInfo? = AppData?.imageList?[indexPath.row]
cell.display(info: imgInfo)
cell.delegate = self
return cell
}
}
extension Controller: PhotoCollectionViewCellDelegate {
func photoCollectionViewCell(didPressCloseBtn cell: PhotoCollectionViewCell) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
if let imgInfo: PhotoInfo = AppData?.imageList?[indexPath.row] {
displayAlert(for: imgInfo)
}
}
}
extension Controller: FotoDeleteAlertDelegate {
func fotoDeleteAlert(
didPressDelete view: FotoDeleteAlert, for item: PhotoInfo?
) {
guard let item: PhotoInfo = item else { return }
deleteWebservices(item.projectUnitImageId)
}
}
protocol PhotoCollectionViewCellDelegate: class {
func photoCollectionViewCell(didPressCloseBtn: PhotoCollectionViewCell)
}
class PhotoCollectionViewCell: UICollectionViewCell {
weak var delegate: PhotoCollectionViewCellDelegate?
var closeIcon: UIButton! {
didSet {
button.addTarget(
self, action: #selector(closeTap), for: .touchUpInside
)
}
}
func display(info: PhotoInfo?) {
imageView.isHidden = info == nil
closeIcon.isHidden = info == nil
addIcon.isHidden = info != nil
if let info = info {
imageView.image = UIImage(url: URL(string: info.url))
}
}
#objc func closeTap() {
delegate?.photoCollectionViewCell(didPressCloseBtn: self)
}
}
protocol FotoDeleteAlertDelegate: class {
func fotoDeleteAlert(
didPressDelete view: FotoDeleteAlert, for item: PhotoInfo?
)
}
class FotoDeleteAlert {
weak var delegate: FotoDeleteAlertDelegate?
var deleteButton: UIButton! {
didSet {
button.addTarget(
self, action: #selector(deleteTap), for: .touchUpInside
)
}
}
private var item: PhotoInfo?
func display(item: PhotoInfo) {
self.item = item
}
#objc func deleteTap() {
delegate?.fotoDeleteAlert(didPressDelete: self, for: item)
}
}
You need
guard let id = AppData?.imageList?[row].projectUnitImageId else { return }
deleteWebservices(id)
Tags are a fragile way to find the particular cell that a user interacts with. Instead, I suggest using the coorindates of the buttons.
I wrote an answer to this thread: swift: how to get the indexpath.row when a button in a cell is tapped?
In that answer I wrote an extension to UITableView, indexPathForView(_:) That function takes a view (which is contained by the table view cell ) and returns the IndexPath of the cell that contains that view.
You can use that exact same approach for collection views. Table views have the function indexPathForRow(at:) and collection views have the equivalent function indexPathForItem(at:).
The extension for a UICollection view would look something like this: (not tested)
import UIKit
public extension UICollectionView {
/**
This method returns the indexPath of the cell that contains the specified view
- Parameter view: The view to find.
- Returns: The indexPath of the cell containing the view, or nil if it can't be found
*/
func indexPathForView(_ view: UIView) -> IndexPath? {
let center = view.center
//The center of the view is a better point to use, but we can only use it if the view has a superview
guard let superview = view.superview else {
//The view we were passed does not have a valid superview.
//Use the view's bounds.origin and convert from the view's coordinate system
let origin = self.convert(view.bounds.origin, from: view)
let indexPath = self.indexPathForItem(at: origin)
return indexPath
}
let viewCenter = self.convert(center, from: superview)
let indexPath = self.indexPathForItem(at: viewCenter)
return indexPath
}
}
Refactor your FotoDeleteAlert to have an imgID property. Have its didDeleteButtonClicked method pass back the image ID, not the tapped button:
protocol handleDeleteAction {
func didDeleteButtonClickedForImageID(_: Integer)
}
Then you would need to rewrite your removeImage(_:) function to take the gesture recognizer and use that to find the IndexPath:
#objc func removeImage(_ tapper: UIGetstureRecognizer) {
//Find the view associated with the tap gesture recognizer
guard let view = tapper.view,
//use the view to find the indexPath of the cell
let indexPath = collectionView. indexPathForView(view) else {
return
}
let imgId = AppData?.imageList[indexPath.row].projectUnitImageId
let fotoXib = Bundle.main.loadNibNamed("FotoDeleteAlert", owner: self, options: nil)
let alertView = fotoXib?.first as! FotoDeleteAlert
alertView.delegate = self
//Pass the image ID to the FotoDeleteAlert
alertView.imgID = imgID
self.view.addSubview(alertView)
}
And then in your delete handler for the FotoDeleteAlert, you can fetch the image ID and use that to issue the delete command to your server.

Set the button image according to selection and default state

This is my code.
class NamePictureCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel?
#IBOutlet weak var buttonType: UIButton?
func setOptions(Options1:NH_OptionsModel)
{
self.nameLabel?.text = Options1.values
}
// var item: NH_QuestionListModel? {
// didSet {
// self.nameLabel?.text = item?.buttontype
// }
// }
static var nib:UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
In viewController:-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
// print(model.answerType?.hashValue)
print(model.answerType)
print(model.answerType?.rawValue)
switch model.answerType {
case .NHAnswerRadioButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NamePictureCell.identifier) as? NamePictureCell {
// cell.item = model
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath))
// print(cell.item)
return cell
}
case .NHAnswerCheckboxButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: AboutCell.identifier, for: indexPath) as? AboutCell {
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath)) // cell.item = item
return cell
}
case .NHAnswerSmileyButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: FriendCell.identifier) as? FriendCell{
cell.textLabel?.text = ""
return cell
}
case .NHAnswerStarRatingButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: EmailCell.identifier) as? EmailCell {
cell.textLabel?.text = ""
return cell
}
case .NHAnswerTextButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier:AttributeCell.identifier, for: indexPath) as? AttributeCell{
cell.textLabel?.text = ""
// cell.item = item
return cell
}
default:
return UITableViewCell()
}
return UITableViewCell()
}
And the model is :-
class NH_QuestionListModel: NSObject {
var dataListArray33:[NH_OptionsModel] = []
var id:Int!
var question:String!
var buttontype:String!
var options:[String]?
var v:String?
var answerType:NHAnswerType?
var optionsModelArray:[NH_OptionsModel] = []
init(dictionary :JSONDictionary) {
guard let question = dictionary["question"] as? String,
let typebutton = dictionary["button_type"] as? String,
let id = dictionary["id"] as? Int
else {
return
}
// (myString as NSString).integerValue
self.answerType = NHAnswerType(rawValue: Int(typebutton)!)
if let options = dictionary["options"] as? [String]{
print(options)
print(options)
for values in options{
print(values)
let optionmodel = NH_OptionsModel(values: values)
self.optionsModelArray.append(optionmodel)
}
}
self.buttontype = typebutton
self.question = question
self.id = id
}
}
In the tableview cell of the NamePictureCell, I have one label and one radio button.
In the xib of this cell. I set the following details for the button.
On default-One image given,
On Selected - another image given
So my question is according my api-
button type - 1 then at normal state the default image should display and on selecting the button the selected image should display.
How to do?
You can use following code to display default and selected button image :
buttonType.setImage(UIImage(named: "defaultImage")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
buttonType.setImage(UIImage(named: "selectedImage")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)

Resources