Remove highlighted text from a cell in TableView - swift

Depending on the status of each pin in the map, each cell in the TableView displays a different color. For changing each color I've not used UIColor.someColor() method, in fact I've used:
UIColor(red: 28/255, green: 198/255, blue: 25/255, alpha: 0.4) //Light red
I would like to remove that highlighted color that is appearing inside each cell. Don't k now if this is a code issue or is something that is inside the TableView/Cell atributes.
I am setting the colors inside the ViewController:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: cellIdentifier)
}
cell!.textLabel!.text = myFeed.objectAtIndex(indexPath.row).objectForKey("NOMBRE") as? String
var aux: String = "BLIBRES"
var aux2: String = "ALIBRES"
var estado: String = "ESTADO"
cell!.detailTextLabel!.text = "Anclajes Libres: \(myFeed.objectAtIndex(indexPath.row).objectForKey(aux2)!) | Bicicletas Libres: \(myFeed.objectAtIndex(indexPath.row).objectForKey(aux)!)"
if myFeed.objectAtIndex(indexPath.row).objectForKey(estado)! as! String == "NO COMUNICA" {
cell?.backgroundColor = UIColor(red: 28/255, green: 198/255, blue: 25/255, alpha: 0.4)
} else if myFeed.objectAtIndex(indexPath.row).objectForKey(estado)! as! String == "COMUNICA" {
cell?.backgroundColor = UIColor(red: 218/255, green: 71/355, blue: 71/255, alpha: 0.4)
} else if myFeed.objectAtIndex(indexPath.row).objectForKey(estado)! as! String == "ALARMAS" {
cell?.backgroundColor = UIColor(red: 248/255, green: 155/255, blue: 18/255, alpha: 0.4)
}
return cell!
}

Solved!
I did not know that apart from setting a background color to the cell itself, you can set a background color to the text (and also detailText) of the cell. Inside the func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { } method add the following:
cell?.textLabel?.backgroundColor = UIColor.clearColor()
cell?.detailTextLabel?.backgroundColor = UIColor.clearColor()
And then the text is displayed correctly without the borders that looked like a highlighted text when setting a custom background color to a cell.

Related

Edit collectionView Cells in UICollectionView

I am creating an app programitcally (on my first try). I have managed to create a collection view and on the click of the add button in the navigation bar a new cell appears. I want to be able to set all cells created to be editable (in other words show the delete button on the cells) when the edit button in the navigation bar is clicked. Currently no matter what I try whether I click on edit or not, nothing happens. I have tried hiding the UIImage of the button as well as the button by calling a function created in the cell class when the edit button is clicked and have also tried moving this function to the ViewController Class, app runs but code doesn't do what it is supposed to.
My Code:
class CollectionViewController: UICollectionViewController, UITextViewDelegate {
// decelrations of variables for use
let cell = ListCell()
let cellId = "cellId"
var numberOfLists = 0
var lists = [String]()
let secondVC = TableViewController()
// for learning purposes: codes sets up the view programitcally along with what is in scenedelagate
override func viewDidLoad() {
super.viewDidLoad()
setCollectionView()
}
//Function that will generate the collectionView
func setCollectionView() {
collectionView.register(ListCell.self, forCellWithReuseIdentifier: cellId)
collectionView.backgroundColor = .white
navigationItem.title = "Lists"
navigationController?.navigationBar.barTintColor = UIColor(white: 200/255, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.boldSystemFont(ofSize: 20)]
navigationItem.leftBarButtonItem = editButtonItem
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
collectionView.delegate = self //runs the delegate flow methods
collectionView.dataSource = self
}
// to do with enabling editing in CV - function tied to edit button
override func setEditing(_ editing: Bool, animated: Bool){
super.setEditing(editing, animated: animated)
if editing {
print ("Editing Mode Enabled")
//cell.showButton()
} else {
print ("Editing Mode Closed")
}
// reloads the view after code is performed
self.collectionView.reloadData()
}
// func when buttons are tapped to add a collection view
#objc func addTapped() {
print("This button should not crash")
numberOfLists += 1
navigationController?.pushViewController(secondVC, animated: true)
collectionView.reloadData()
}
}
// the following block of code has to do with the set up of the collectionView
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
// this code should speficiy how many cells you are going to have in your collectionview
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfLists
}
// this code lets you reuse a cell
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)-> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ListCell
cell.deleteButton.setImage(UIImage.init(named: "delete"), for: .normal)
return cell
}
// this code sets the sizing of the cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (view.frame.width / 2) - 16, height: 100)
}
// where to place the cell on the screen
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 8, left: 9, bottom: 8, right: 8)
}
// this function just checks to see if the cell is selected
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
navigationController?.pushViewController(secondVC, animated: true)
}
}
//this class sets up the collectionViewCell
class ListCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
fileprivate func setupCell(){
let colors = cellRandomBackgroundColors()
self.backgroundColor = colors[0]
self.addSubview(listNameLabel)
roundCorner()
setCellShadow()
self.addSubview(deleteButton)
deleteButton.addTarget(self, action: #selector(deleteCell), for: .touchUpInside)
}
#objc func deleteCell() {
print ("this button works")
}
func showButton() {
deleteButton.isHidden = true
print ("this is supposed to work")
}
func roundCorner() {
self.contentView.layer.cornerRadius = 50.0
self.contentView.layer.masksToBounds = true
self.contentView.layer.borderWidth = 1.0
self.contentView.layer.borderColor = UIColor.clear.cgColor
}
func setCellShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 1)
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 1.0
self.layer.masksToBounds = false
self.layer.cornerRadius = 3
self.clipsToBounds = false
}
func cellRandomBackgroundColors() -> [UIColor] {
//Colors
let red = [#colorLiteral(red: 0.9654200673, green: 0.1590853035, blue: 0.2688751221, alpha: 1),#colorLiteral(red: 0.7559037805, green: 0.1139892414, blue: 0.1577021778, alpha: 1)]
let orangeRed = [#colorLiteral(red: 0.9338900447, green: 0.4315618277, blue: 0.2564975619, alpha: 1),#colorLiteral(red: 0.8518816233, green: 0.1738803983, blue: 0.01849062555, alpha: 1)]
let orange = [#colorLiteral(red: 0.9953531623, green: 0.54947716, blue: 0.1281470656, alpha: 1),#colorLiteral(red: 0.9409626126, green: 0.7209432721, blue: 0.1315650344, alpha: 1)]
let yellow = [#colorLiteral(red: 0.9409626126, green: 0.7209432721, blue: 0.1315650344, alpha: 1),#colorLiteral(red: 0.8931249976, green: 0.5340107679, blue: 0.08877573162, alpha: 1)]
let green = [#colorLiteral(red: 0.3796315193, green: 0.7958304286, blue: 0.2592983842, alpha: 1),#colorLiteral(red: 0.2060100436, green: 0.6006633639, blue: 0.09944178909, alpha: 1)]
let greenBlue = [#colorLiteral(red: 0.2761503458, green: 0.824685812, blue: 0.7065336704, alpha: 1),#colorLiteral(red: 0, green: 0.6422213912, blue: 0.568986237, alpha: 1)]
let kindaBlue = [#colorLiteral(red: 0.2494148612, green: 0.8105323911, blue: 0.8425348401, alpha: 1),#colorLiteral(red: 0, green: 0.6073564887, blue: 0.7661359906, alpha: 1)]
let skyBlue = [#colorLiteral(red: 0.3045541644, green: 0.6749247313, blue: 0.9517192245, alpha: 1),#colorLiteral(red: 0.008423916064, green: 0.4699558616, blue: 0.882807076, alpha: 1)]
let blue = [#colorLiteral(red: 0.1774400771, green: 0.466574192, blue: 0.8732826114, alpha: 1),#colorLiteral(red: 0.00491155684, green: 0.287129879, blue: 0.7411141396, alpha: 1)]
let bluePurple = [#colorLiteral(red: 0.4613699913, green: 0.3118675947, blue: 0.8906354308, alpha: 1),#colorLiteral(red: 0.3018293083, green: 0.1458326578, blue: 0.7334778905, alpha: 1)]
let purple = [#colorLiteral(red: 0.7080290914, green: 0.3073516488, blue: 0.8653779626, alpha: 1),#colorLiteral(red: 0.5031493902, green: 0.1100070402, blue: 0.6790940762, alpha: 1)]
let pink = [#colorLiteral(red: 0.9495453238, green: 0.4185881019, blue: 0.6859942079, alpha: 1),#colorLiteral(red: 0.8123683333, green: 0.1657164991, blue: 0.5003474355, alpha: 1)]
let colorsTable: [Int: [UIColor]] = [0: red, 1: orangeRed, 2: orange, 3: yellow, 4: green, 5: greenBlue, 6: kindaBlue, 7: skyBlue, 8: blue, 9: bluePurple, 10: bluePurple, 11: purple, 12: pink]
let randomColors = colorsTable.values.randomElement()
return randomColors!
}
let deleteButton: UIButton = {
let deleteButton = UIButton(frame: CGRect(x:2,y:2,width:70,height:30))
return deleteButton
}()
let listNameLabel: UILabel = {
let listLabel = UILabel(frame: CGRect(x:2,y:50,width:70,height:30))
listLabel.text = "Data entry on Second View"
listLabel.font = UIFont.boldSystemFont(ofSize: 12)
listLabel.backgroundColor = .green
listLabel.translatesAutoresizingMaskIntoConstraints = false
listLabel.tag = 1
return listLabel
}()
let iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Folder")
imageView.contentMode = .scaleAspectFit
return imageView
}()
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Edit Button on Cells that doesn't disappear

How to pass data from UITableView to UIViewController without segue

I need to pass the title of Row in UITableView to my ViewController. I don't have VC in storyboard (I've created it by code). So I can't use segue.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
cell.textLabel?.tintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
var titleOfFood = String()
if searching == true {
titleOfFood = searchedFoods[indexPath.row].title
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
print(titleOfFood)
} else {
titleOfFood = foods[indexPath.row].title
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
print(titleOfFood)
}
let controller = EatenFoodViewController()
let transitionDelegate = SPStorkTransitioningDelegate()
controller.transitioningDelegate = transitionDelegate
controller.modalPresentationStyle = .custom
//controller.delegate = self
transitionDelegate.customHeight = 620
transitionDelegate.showIndicator = false
self.present(controller, animated: true, completion: nil)
}
I need to pass titleOfFood to EatenFoodViewController
You don't need to have a segue to send data to the destination vc , you can simply do
controller.titleOfFood = arr[indexPath.row].title // assuming you have an array of models
OR
controller.titleOfFood = cell.textLabel!.text!
class EatenFoodViewController:UIViewController {
var titleOfFood = ""
}

Cannot unselect the checkmark when scroll the tableView

I'm trying to do checkmark button in tableViewCell. The checkmark image will be hide/showing when user tap on the checkmark button. The problem I'm facing right now is checkmark button acting weird when I scroll the table view which is I need to double tap to unselect the checkmark.
When I do not scroll the tableView it's working great. Below are the video and code. Thanks in advance.
https://youtu.be/cQBIuIXJlRY
func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "dtvc") as! DeviceTableViewCell
let scannedDevice = devices[indexPath.row]
// Set the tag & addTarget for addButton
cell.addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
cell.addButton.isEnabled = true
cell.addButton.tag = indexPath.row
cell.configureCell(with: scannedDevice)
cell.isSelected = checked[indexPath.row] ?? false
print("cell isSelected at \(indexPath.row) cellForRow \(cell.isSelected)")
print("checked value at \(indexPath.row) is \(checked[indexPath.row])")
if checked[indexPath.row] == true {
cell.deviceMake.textColor = UIColor.white
cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
cell.addButton.bgColor = UIColor.green
} else {
cell.deviceMake.textColor = UIColor.gray
cell.backgroundColor = UIColor.clear
cell.addButton.setImage(nil, for: .normal)
cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
}
return cell
}
#objc func addButtonTapped(_ sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
let scannedDevice = devices[sender.tag]
let cell = tableView.cellForRow(at: indexPath) as! DeviceTableViewCell
cell.isSelected = !cell.isSelected
print("cell.isSelected is at button \(sender.tag) tapped is \(cell.isSelected)")
if cell.isSelected == true {
// Main color RGB is 233,72,85 ... hex is E94855
cell.deviceMake.textColor = UIColor.white
cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
cell.addButton.bgColor = UIColor.green
checked[sender.tag] = cell.isSelected
print("Checked 1 at tag \(sender.tag) is \(checked[sender.tag])")
//show selectedDeviceView
if selectedDeviceView.isHidden {
UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
self.selectedDeviceViewTopConstraint.constant = 0
self.selectedDeviceView.isHidden = false
}, completion: nil)
}
}
else {
cell.deviceMake.textColor = UIColor.gray
cell.backgroundColor = UIColor.clear
cell.addButton.setImage(nil, for: .normal)
cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
checked[sender.tag] = cell.isSelected
print("Checked 2 at tag \(sender.tag) is \(checked[sender.tag])")
}
}
First of all put the selected state into the devices class/struct rather than using an extra array
class Device {
var isSelected = false
...
Second of all don't think in terms of the view think in terms of the model. That means toggle isSelected in the model and reload the row. The benefit is that the view is manipulated reliably only in cellForRow.
For example
#objc func addButtonTapped(_ sender: UIButton) {
let indexPath = IndexPath(row: sender.tag, section: 0)
devices[indexPath.row].isSelected.toggle()
self.tableView.reloadRows(at: [indexPath], with: .none)
if devices[indexPath.row].isSelected && selectedDeviceView.isHidden {
UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
self.selectedDeviceViewTopConstraint.constant = 0
self.selectedDeviceView.isHidden = false
}, completion: nil)
}
}
And in cellForRow change
cell.isSelected = scannedDevice.isSelected

custom TableViewCell out of order?

ive been having a lot of issues with my tableview getting out of order or losing a custom image in the tableview cell. I have been doing a lot of research and found a few helpful things on it but none seem to resolve my issue. It seems to be an issue with the reuse cell. I also have an if statement to change an images background on the custom cell depending on what button you press. Any help would be awesome thanks.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! expenseTableViewCell
let expense = expenses[indexPath.row]
cell.expenseName.text = expenses[indexPath.row].ename
cell.expenseCost.text = "$" + expenses[indexPath.row].ecost!
cell.expenseDue.text = expenses[indexPath.row].edue
//CHANGE BACKGROUND VIEW COLOR
if expense.picture == "1"{
cell.picture.backgroundColor = UIColor(red: 255/255, green: 116/255, blue: 115/255, alpha:1)
}
if expense.picture == "2"{
cell.picture.backgroundColor = UIColor(red: 30/255, green: 192/255, blue: 255/255, alpha:1)
}
return cell
}
Try this instead:
if expense.picture == "1"{
cell.picture.backgroundColor = UIColor(red: 255/255, green: 116/255, blue: 115/255, alpha:1)
} else if expense.picture == "2"{
cell.picture.backgroundColor = UIColor(red: 30/255, green: 192/255, blue: 255/255, alpha:1)
}
Because you are reusing cells, you can't have if statements the way you are writing them. You have to use else if otherwise the cells that stay in memory mess things up.

swift detailTextLabel not showing up

Ive checked around stackOverFlow for a solution but it seemed like it still didnt work for my code.. my detailTextLabel still does not show up :(
Wondering what I am doing wrong, here's my code
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
// display our ranked data
cell.textLabel?.text = "\(championListInGame[indexPath.row])"
if let url = NSURL(string: "http://ddragon.leagueoflegends.com/cdn/img/champion/loading/\(championListInGame[indexPath.row])_0.jpg"){
if let urlData = NSData(contentsOfURL: url){
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView?.image = UIImage(data: urlData)
}
}
if victory[indexPath.row] == true {
cell.backgroundColor = UIColor.blueColor()
cell.detailTextLabel?.text = " "+"victory!"
} else {
cell.backgroundColor = UIColor.redColor()
cell.detailTextLabel?.text = " "+"defeat!"
}
return cell
}
my victory nor defeat showed up in my table cells however, the color, image, and text all showed up just as the way I wanted.
On the side note, can someone teach me how do I choose colors like baby blue or baby red ? the default red and blue is too strong for my app :(
Thanks for the help guys!
The default cell style doesn't have a detailTextLabel. You need to use .Value1 or .Subtitle as the UITableViewCellStyle:
var cell = UITableViewCell(style: .Value1, reuseIdentifier: nil)
You can use the UIColor:red:green:blue:alpha: constructor to make custom colors. The values all vary from 0.0 to 1.0. You can look on the web for colors. If they are specified with values in the 0 to 255 range, you can convert them by dividing the values by 255.0:
let babyRed = UIColor(red: 1.0, green: 0.6, blue: 0.6, alpha: 1.0)
let babyBlue = UIColor(red:128.0/255.0, green: 178.0/255.0, blue: 255.0/255.0, alpha: 1.0)