Reset all buttons after pressing the next button - ios

I need to change the image from the button to another after clicking on the button. I did this with the help of setBackgroundImage(). But how do I change the image of all buttons at once and change the image only to the button that is pressed...
![button set][1]
My viewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
self.tableView.separatorStyle = .none
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UIT
cell.TitleLabel.text=dataMas[indexPath.row]
cell.name.text = titleTrack[indexPath.row]
cell.btns.tag = indexPath.row
cell.btns.addTarget(self, action: #selector(ViewController.PlayTrack(_:)), for: UIControlEvents.touchUpInside )
return cell
}
and cell class
import UIKit
class UIT: UITableViewCell {
#IBOutlet weak var btns: UIButton!
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var name: UILabel!
override func awakeFromNib() {
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
}

try this inside your ViewController.PlayTrack:
var numberOfButtons: Int = 5
#IBOutlet weak var btns: UIButton!
for i in 1...numberOfButtons {
if btns.tag == i {
// SET IMAGE TO BTN HERE.
}
}

Related

Swift 5 Collapsible table header

I have to do this implementation, I need a list of cells representing month periods, where each one is collapsed, and when clicked it shows its content, I used two cells prototypes based on some tutorials I found but I'm really new into swift programming, I can't get the expected result, I share some screens and actual code. Hope someone could help me.
class BillingListCell: UITableViewCell{
#IBOutlet weak var billWrapper: UIView!
#IBOutlet weak var billTotal: UILabel!
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
}
}
class BillingListHeaderCell: UITableViewCell{
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var numberLabel: UILabel!
#IBOutlet weak var statusButton: UIButton!
func setExpanded() {
statusButton.setImage(UIImage(systemName: "chevron.up"), for: .normal)
}
func setCollapsed() {
statusButton.setImage(UIImage(systemName: "chevron.down"), for: .normal)
}
}
class BillingListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var billingListTableView: UITableView!
var paymentArray: [String] = ["data","data2", "data3"]
private let numberOfActualRowsForSection = 1
func numberOfSections(in tableView: UITableView) -> Int {
return paymentArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// First will always be header
return false ? (1+numberOfActualRowsForSection) : 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row == 0){
let cell = tableView.dequeueReusableCell(withIdentifier: "BillingListHeaderCell", for: indexPath) as! BillingListHeaderCell
cell.setCollapsed()
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: "BillingListCell", for: indexPath) as! BillingListCell
cell.billWrapper.layer.cornerRadius = 15
cell.billWrapper.layer.borderWidth = 1
cell.billWrapper.layer.borderColor = UIColor.blue.cgColor
cell.billTotal.text = "1234"
return cell
}
}

Having trouble connecting my CustomCell.xib to my tableView in the storyboard

I Have to do an app for recipes and it shows me different recipes in my tableView, and i just want to implement my CustomCell (from a xib file) to my storyboard and I don't know how to connect it to show my data (I already checked my identifier) here's the code of my controller :
class SearchRecipe: UIViewController, ShowAlert {
var recipeData = RecipeDataModel()
var recipe = [String]()
#IBOutlet weak var tableViewSearch: UITableView!
override func viewDidLoad() {
self.tableViewSearch.rowHeight = 130
}
func updateRecipeData(json: JSON){
if let ingredients = json["hits"][0]["recipe"]["ingredientLines"].arrayObject{
recipeData.ingredientsOfRecipe = ingredients[0] as! String
recipeData.cookingTime = json["hits"][0]["recipe"]["totalTime"].stringValue
recipeData.recipe = json["hits"][0]["recipe"]["label"].stringValue
recipeData.recipeImage = json["hits"][0]["recipe"]["image"].stringValue
}
else {
print("Problem")
}
//self.tableViewSearch.reloadData()
}
}
extension SearchRecipe: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipe.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customRecipeCell", for: indexPath) as! CustomRecipeCell
getRecipesDisplay(in: cell, from: recipeData , at: indexPath)
return cell
}
func getRecipesDisplay(in cell: CustomRecipeCell, from recipeModel: RecipeDataModel, at indexPath: IndexPath){
cell.recipeTitle.text = recipeData.recipe
cell.recipeInfos.text = recipeData.ingredientsOfRecipe
cell.timerLabel.text = recipeData.cookingTime
}
}
and this is the code my xib file :
class CustomRecipeCell: UITableViewCell {
#IBOutlet weak var recipeTitle: UILabel!
#IBOutlet weak var recipeInfos: UILabel!
#IBOutlet weak var cellImageBackground: UIImageView!
#IBOutlet weak var likeAndTimerView: UIView!
#IBOutlet weak var likeImage: UIImageView!
#IBOutlet weak var timerImage: UIImageView!
#IBOutlet weak var likeLabel: UILabel!
#IBOutlet weak var timerLabel: UILabel!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func awakeFromNib() {
super.awakeFromNib()
activityIndicator.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
In ViewDidLoad, you must register your cell this way:
override func viewDidLoad() {
tableViewSearch.register(UINib(nibName:" /* NAME OF YOUR XIB FILE */ ", bundle: nil), forCellReuseIdentifier: "customRecipeCell")
}
You also have to edit the size of your cell in the attribute inspector of your custom cell and of your table view

Custom UITableViewCell doesn't show all contents

My problem is that I have a custom cell that doesn't show all the contents showed in the storyboard.
cellForRowAt code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "menuCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MenuTableCell
cell?.accessoryType = .disclosureIndicator;
cell?.altriPiattiLabel.isHidden = true
cell?.piatto3Label.isHidden = true
cell?.sceltaMiglioreLabel.isHidden = true
cell?.numeroMenuLabel.text = "MenĂ¹ \(indexPath.row+1)"
cell?.numeroPiattiLabel.text = "\(menus[indexPath.row].getPiatti().count) piatti"
cell?.piatto1Label.text = "Piatto 1: \(menus[indexPath.row].getPiatti()[0].getDescrizione())"
cell?.piatto2Label.text = "Piatto 2: \(menus[indexPath.row].getPiatti()[1].getDescrizione())"
if (menus[indexPath.row].getPiatti().count >= 3) {
cell?.piatto3Label.isHidden = false
if(menus[indexPath.row].getPiatti().count > 3) {
cell?.altriPiattiLabel.isHidden = false
}
print("heeeeere")
cell?.piatto3Label.text = "Piatto 3: \(menus[indexPath.row].getPiatti()[2].getDescrizione())"
}
if(indexPath.row == 0) {
cell?.sceltaMiglioreLabel.isHidden = false
}
if(indexPath.row == menus.count-1) {
cell?.sceltaMiglioreLabel.isHidden = false
cell?.sceltaMiglioreLabel.text = "scelta peggiore"
cell?.sceltaMiglioreLabel.backgroundColor = UIColor.red
}
return cell!
}
Custom cell code:
import UIKit
class MenuTableCell: UITableViewCell {
#IBOutlet weak var numeroMenuLabel: UILabel!
#IBOutlet weak var sceltaMiglioreLabel: UITextView!
#IBOutlet weak var piatto1Label: UILabel!
#IBOutlet weak var piatto2Label: UILabel!
#IBOutlet weak var piatto3Label: UILabel!
#IBOutlet weak var cliccaPerInfoLabel: UILabel!
#IBOutlet weak var numeroPiattiLabel: UILabel!
#IBOutlet weak var altriPiattiLabel: UILabel!
override func layoutSubviews() {
sceltaMiglioreLabel.layer.masksToBounds = true;
sceltaMiglioreLabel.layer.cornerRadius = 10.0
altriPiattiLabel.layer.masksToBounds = true;
altriPiattiLabel.layer.cornerRadius = 10.0
}
override func awakeFromNib() { super.awakeFromNib() }
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Storyboard settings:
My cell settings in the storyboard
"sceltaMiglioreLabel" and the disclosureIndicator are never showed up in the simulator.
Thanks in advance.

Swift -> my prototype cell (UITableViewCell) doesn't show in my UIViewController with a UITableView

My storyboard looks like this
and my code is the following
UIViewController
class DownLoadSoundsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: View Controller Properties
let viewName = "DownLoadSoundsViewController"
#IBOutlet weak var visualEffectView: UIVisualEffectView!
#IBOutlet weak var dismissButton: UIButton!
#IBOutlet weak var downloadTableView: UITableView!
// MARK: Properties
var soundPacks = [SoundPack?]() // structure for downloadable sounds
override func viewDidLoad() {
super.viewDidLoad()
downloadTableView.dataSource = self
downloadTableView.delegate = self
downloadTableView.register(DownLoadTableViewCell.self, forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfSoundPacks
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let method = "tableView.cellForRowAt"
//if (indexPath as NSIndexPath).section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "downloadTableViewCell", for: indexPath) as! DownLoadTableViewCell
cell.backgroundColor = UIColor.green
if soundPacks[(indexPath as NSIndexPath).row]?.price == 0 {
cell.soundPackPriceUILabel.text = "FREE"
} else {
cell.soundPackPriceUILabel.text = String(format: "%.2", (soundPacks[(indexPath as NSIndexPath).row]?.price)!)
}
//cell.textLabel?.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
cell.soundPackTitleUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.soundPackTitle
cell.soundPackAuthorUILabel.text = soundPacks[(indexPath as NSIndexPath).row]?.author
cell.soundPackShortDescription.text = soundPacks[(indexPath as NSIndexPath).row]?.shortDescription
cell.soundPackImage.image = UIImage(named: "Placeholder Icon")
DDLogDebug("\(viewName).\(method): table section \((indexPath as NSIndexPath).section) row \((indexPath as NSIndexPath).row))")
return cell
//}
}
UItableViewCell
class DownLoadTableViewCell: UITableViewCell {
#IBOutlet weak var soundPackImage: UIImageView!
#IBOutlet weak var soundPackTitleUILabel: UILabel!
#IBOutlet weak var soundPackAuthorUILabel: UILabel!
#IBOutlet weak var soundPackShortDescription: UILabel!
#IBOutlet weak var soundPackPriceUILabel: UILabel!
let gradientLayer = CAGradientLayer()
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
}
}
But I get the following;
I am sure I am doing something small incorrectly, but as of yet can't figure it out. Looked through many examples included my own code where I have gotten this working before.
Not a single one of my settings for the tableview are getting invoked except the number of cells. But everything in;
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{...}
is not working.
Help is appreciated.
I think you need to reload the tableView after getting data from Firebase
self.saveMixesTableView.reloadData()

How to alter a button in cell on click in swift ios?

I have a table layout inside a view which as a custom cell,The problem I'm facing is that the cells inside has a button i want to hide the button in cell on clicking it(only the one that is clicked should be hidden) how can i do thing in correct method?
ScrollCell.swift
class ScrollCell: UITableViewCell {
#IBOutlet weak var ProfilePic: SpringImageView!
#IBOutlet weak var UserName: SpringButton!
#IBOutlet weak var Closet: UILabel!
#IBOutlet weak var Style: UILabel!
//------//
#IBOutlet weak var MianImg: UIImageView!
//-------//
#IBOutlet weak var ProductName: UILabel!
#IBOutlet weak var LoveCount: UIButton!
#IBOutlet weak var Discount: UILabel!
#IBOutlet weak var OrginalPrice: UILabel!
#IBOutlet weak var Unliked: UIButton!
#IBOutlet weak var Liked: UIButton!
#IBOutlet weak var Comment: UIButton!
#IBOutlet weak var Share: SpringButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
ProfilePic.layer.cornerRadius = ProfilePic.bounds.height / 2
ProfilePic.clipsToBounds = true
}
}
ScrollController.swift
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // however many sections you need
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(try! Realm().objects(Feed))
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
return tan.count // however many rows you need
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get an instance of your cell
cell = tableView.dequeueReusableCellWithIdentifier("ScrollCellDqueue", forIndexPath: indexPath) as! ScrollCell
IndexPath = indexPath.row
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
cell.ProfilePic.kf_setImageWithURL(NSURL(string:tan[indexPath.row].ProfilePic)!)
cell.UserName.setTitle(tan[indexPath.row].FullName, forState: .Normal)
cell.Style.text = tan[indexPath.row].StyleType
if tan[indexPath.row].UserType == "store_front"{
cell.Closet.text = "Store Front"
}else if tan[indexPath.row].UserType == "normal"{
cell.Closet.text = "Pri Loved"
}
//-----//
var SingleImage:String = ""
var ImageArray = tan[indexPath.row].ImageArraySet.componentsSeparatedByString(",")
SingleImage = ImageArray[0]
cell.MianImg.kf_setImageWithURL(NSURL(string:SingleImage)!)
//-----//
cell.ProductName.text = tan[indexPath.row].ItemName
cell.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
cell.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
cell.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
if(tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = true
cell.Liked.hidden = false
}
else if (!tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = false
cell.Liked.hidden = true
}
cell.Unliked.tag = tan[indexPath.row].ID
cell.Liked.tag = tan[indexPath.row].ID
return cell
}
#IBAction func LikeBtn(sender: AnyObject) {
print(sender.tag)
print(IndexPath)
//here i want to know who i can hide the button i have clicked ?
}
Here i want to access the cell in which button is clicked and make changes to UI item inside that cell how can i do that ?
There are many ways to do it. One possible solution is use block.
Add this to ScrollCell
var didLikedTapped: (() -> Void)?
and receive the event of the LikedButton in the cell
#IBAction func LikeBtn(sender: AnyObject) {
didLikedTapped?()
}
Then in cellForRowAtIndexPath of viewController add this
cell.didLikedTapped = {[weak self] in
print(IndexPath)
}
Liked is uibutton in ScrollCell, i don't known, why can you add IBAction for it in ScrollController? . You must implement it in ScrollCell And code:
#IBAction func LikeBtn(sender: UIButton) {
print(sender.tag)
sender.hiden = true
}
And i think, if you have only one UIbutton, it will better. In there, like and unlike is 2 state of uibutton(seleted and none). When you click the button, change it's state
Update:
class sampleCell: UITableViewCell{
#IBOutlet var btnLike : UIButton!
#IBOutlet var btnUnLike : UIButton! // frame of 2 button is equal
override func awakeFromNib() {
super.awakeFromNib()
self.btnUnLike.hidden = true
// ...
}
func updateData(data:AnyObject){ // data's type is Feed
// set data for cell
// i think you should implement in here. and in ScollController call : cell.updateData() , it's better
/* e.x
self.ProductName.text = tan[indexPath.row].ItemName
self.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
self.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
self.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
*/
}
#IBAction func likeTap(sender:UIButton){ // rememeber set outlet event for btnLike and btnUnLike is this function
if sender == self.btnLike{
self.btnLike.hidden = true
self.btnUnLike.hidden = false
// do s.t
}else if sender == self.btnUnLike{
self.btnLike.hidden = false
self.btnUnLike.hidden = true
// do s.t
}
}
}
Check if the following code help
#IBAction func LikeBtn(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
}
give the LikeBtn the property indexpath, in cellForRowAtIndexPath method, pass the indexPath to the LikeBtn, then you will know which cell's LikeBtn clicked.
class LikeBtn: UIButton {
var indexPath: NSIndexPath?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// here pass the indexpath to your button
cell.likeBtn.indexPath = indexPath
return cell
}
#IBAction func likeTap(sender: LikeBtn){
if let indexPath = sender.indexPath {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
//here you will know the exact cell, now you can hide or show your buttons
}
}
}

Resources