Custom UITableViewCell doesn't show all contents - ios

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.

Related

How to copy a String by pressing a button inside UITableView Cell in Swift

I have an array of data "electricity" which I am getting from the server. I have a button inside a UITableView Cell name "copyPinButton". Inside 'cellForRowAt indexPath' I am placing the data necessarily. I want to copy a string value that I am getting from the server by pressing 'copyPinButton'. Thanks in advance.
import UIKit
class ElectricityBillTransactionHistoryViewController: BaseViewController {
#IBOutlet weak var electricityTransactionHistoryTableView: UITableView!
private var electricity = [Electricity]()
override func viewDidLoad() {
super.viewDidLoad()
electricityTransactionHistoryTableView.delegate = self
electricityTransactionHistoryTableView.dataSource = self
electricityTransactionHistory()
}
func electricityTransactionHistory() {
webserviceHandler.transactionHIstory(onCompletion: { (TransactionHistoryResponse) in
if TransactionHistoryResponse.code == 200 {
self.electricity = TransactionHistoryResponse.data?.electricity ?? []
self.electricityTransactionHistoryTableView.delegate = self
self.electricityTransactionHistoryTableView.dataSource = self
self.electricityTransactionHistoryTableView.reloadData()
}else {
self.showDialog(title: nil, message: TransactionHistoryResponse.message ?? K.Messages.DefaultErrorMessage, onDefaultActionButtonTap: nil)
}
}, onFailure: { ( _) in
self.showDialog(title: nil, message: K.Messages.DefaultErrorMessage, onDefaultActionButtonTap: nil)
}, shouldShowLoader: true)
}
}
extension ElectricityBillTransactionHistoryViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return electricity.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "electricityTransactionHistoryTableViewCellId", for: indexPath) as! electricityTransactionHistoryTableViewCell
let electricityData = electricity[indexPath.row]
cell.electricityBillHistoryTitleLabel.text = electricityData.packName
cell.electricityBillTransactionIdLabel.text = "\( electricityData.trackerID ?? 0)"
cell.electricityBillAmountLabel.text = "\(electricityData.paidAmount ?? 0)"
cell.electricityBillPaymentDateLabel.text = Util.getFormattedDateString(inputDateString: electricityData.purchasedDate ?? "", inputDateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", outputDateFormat: "dd MMM yyyy - h:mm a")
return cell
}
}
class electricityTransactionHistoryTableViewCell: UITableViewCell {
#IBOutlet weak var electricityBillContainerView: UIView!
#IBOutlet weak var copyPinButton: UIButton!
#IBOutlet weak var electricityBillImageView: UIImageView!
#IBOutlet weak var electricityBillHistoryTitleLabel: UILabel!
#IBOutlet weak var electricityBillAmountLabel: UILabel!
#IBOutlet weak var electricityBillMonthLabel: UILabel!
#IBOutlet weak var electricityBillTransactionIdLabel: UILabel!
#IBOutlet weak var electricityBillPaymentDateLabel: UILabel!
override func awakeFromNib() {
copyPinButton.layer.masksToBounds = false
copyPinButton.layer.shadowColor = UIColor.gray.cgColor
copyPinButton.layer.shadowOpacity = 0.5
copyPinButton.layer.shadowOffset = CGSize(width: 1.5, height: 0.5)
copyPinButton.layer.shadowRadius = 3
electricityBillContainerView.layer.masksToBounds = false
electricityBillContainerView.layer.shadowColor = UIColor.gray.cgColor
electricityBillContainerView.layer.shadowOpacity = 0.5
electricityBillContainerView.layer.shadowOffset = CGSize(width: 2.0, height: 0.5)
electricityBillContainerView.layer.shadowRadius = 3
}
#IBAction func copyButtonTapped(_ sender: Any) {
}
}
Use UIPasteboard directly
// write to clipboard
UIPasteboard.general.string = "Hello world"
// read from clipboard
let content = UIPasteboard.general.string
Check this question for more detailed answers
You can copy text or string using UIPasteboard like below:
#IBAction func copyButtonTapped(_ sender: Any) {
UIPasteboard.general.string = "Your value"
}

Display pictures in a TableView from Firebase Storage in SWIFT without mistake

I have a chat app where people can talk in a group and a little picture is displayed in each cell to show who is talking. I managed to display these pictures from Firebase storage but it is not always the right picture which is displayed at the right place.
It only works when I go to the previous View Controller and coming back the chat View to see the pictures displayed properly in each cell.
I tried override prepareForReuse() but it's not better. Do you have any idea how I could solve this problem ?
import UIKit
class CustomMessageCell: UITableViewCell {
#IBOutlet weak var messageBody: UILabel!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var messageBubble : UIView!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var messageBodyTextView: UITextView!
#IBOutlet weak var userPicture: UIImageView!
#IBOutlet weak var imageButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
messageBubble.layer.cornerRadius = messageBubble.frame.size.height / 5
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
userPicture.image = nil
messageBodyTextView.text = ""
usernameLabel.text = ""
timeLabel.text = ""
print("prepareforreuse")
}
}
for the class ConversationViewController
class ConversationViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UNUserNotificationCenterDelegate, GADBannerViewDelegate {
// ...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messageArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
cell.userPicture.image = nil
cell.selectionStyle = .none
//...
cell.messageBodyTextView.text = messageArray[indexPath.row].messageBody
cell.usernameLabel.text = messageArray[indexPath.row].name
cell.timeLabel.text = dateToShow
cell.userPicture.layer.cornerRadius = cell.userPicture.frame.height / 2
cell.userPicture.clipsToBounds = true
// Charge image
let imagePath = self.storageRef.reference(withPath:"\(message.uid)/resizes/profilImage_150x150.jpg")
imagePath.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
if let error = error {
cell.userPicture.image = UIImage(named: "emptyProfilPic")
print("Got an error fetching data : \(error.localizedDescription)")
// return
}
if let data = data {
cell.userPicture.image = UIImage(data: data)
}
}
return cell
}
}

How to make selected cell turn a different color for custom cells UITableViewCell

I want to make a selected cell a specific color (UIColor.systemGray). I've tried almost every answer out there but for some reason the way that my cells are it isn't working.
Here is part of my view controller class:
extension CommunicationViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return communicationcells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let communicationCell = communicationcells[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CommunicationCell") as! CommunicationCell
cell.backgroundButton.tag = indexPath.row
cell.backgroundButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
cell.setCommunication(communication: communicationCell)
return cell
}
struct Holder {
static var _myComputedProperty:Int = -1
}
var myComputedProperty:Int {
get {
return Holder._myComputedProperty
}
set(newValue) {
Holder._myComputedProperty = newValue
}
}
#objc func buttonTapped(_ sender: UIButton) {
myComputedProperty = sender.tag
performSegue(withIdentifier: "CommunicationSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailsController = segue.destination as! CommunicationDetailsViewController
detailsController.passthroughstring = String(myComputedProperty)
}
}
And here is my communication cell controller:
class CommunicationCell: UITableViewCell {
#IBOutlet var backgroundcontentView: UIView!
#IBOutlet weak var CommunicationType: UILabel!
#IBOutlet weak var subject: UILabel!
#IBOutlet weak var partnerType: UILabel!
#IBOutlet weak var partnerID: UILabel!
#IBOutlet weak var effectiveFrom: UILabel!
#IBOutlet weak var effectiveTo: UILabel!
#IBOutlet weak var downtimeFrom: UILabel!
#IBOutlet weak var downtimeTo: UILabel!
#IBOutlet weak var backgroundButton: UIButton!
#IBOutlet var collectionOfCommunicationLabels: Array<UILabel>!
func applyTheme() {
for i in 0..<collectionOfCommunicationLabels.count {
collectionOfCommunicationLabels[i].textColor = Theme.current.textColor
collectionOfCommunicationLabels[i].backgroundColor = Theme.current.backgroundColor
}
backgroundcontentView.backgroundColor = Theme.current.backgroundColor
CommunicationType.textColor = Theme.current.textColor
subject.textColor = Theme.current.textColor
partnerType.textColor = Theme.current.textColor
partnerID.textColor = Theme.current.textColor
effectiveFrom.textColor = Theme.current.textColor
effectiveTo.textColor = Theme.current.textColor
downtimeFrom.textColor = Theme.current.textColor
downtimeTo.textColor = Theme.current.textColor
// backgroundButton.backgroundColor = Theme.current.backgroundColor
}
func setCommunication(communication: Communication) {
CommunicationType.text = communication.communicationType
subject.text = communication.subject
partnerType.text = communication.partnerType
partnerID.text = communication.partnerID
effectiveFrom.text = communication.effectiveFrom
effectiveTo.text = communication.effectiveTo
downtimeFrom.text = communication.downtimeFrom
downtimeTo.text = communication.downtimeTo
applyTheme()
}
}
I've tried almost every answer on stack overflow and nothing has worked for me.
Can you please try to implement the didSelectRowAtIndexPath method in addition to the cellForRowAtIndexPath method? In that case, you will not need a background button and also you will get a callback in the didSelectRowAtIndexPath method on tapping any row in the tableview.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
selectCell.backgroundColor = .red //change to any color you want it to change to on selection
performSegue(withIdentifier: "CommunicationSegue", sender: self)
}

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

Reset all buttons after pressing the next button

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.
}
}

Resources