How to show/hide a label by pressing a label in swift? - ios

How to show/hide a label by pressing a label in swift?
how to show/hide a button by pressing a button in swift?
how to show/hide a cell by pressing a cell in swift?
thank you.

For the button:
Create an outlet action for the button. In the method type:
'yourButton'.isHidden = true
For the label
Add a tap gesture recognizer to the label. In the acition for it, type:
'yourLabel'.isHidden = true
For the cell
I don't think it is the way to go. It is better if you follow iOS standards, and delete the row by swiping to the left. Like this:
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}

UILabel will need a gesture recognizer to process a tap:
let gesture = UITapGestureRecognizer(target: self, action: "handleTap:")
label1.addGestureRecognizer(gesture)
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
label2.isHidden = true
}
}
UIButtons will just need to be hooked up to an IBAction in the storyboard:
#IBAction func buttonPressed(_ object:AnyObject)
{
button2.isHidden = true
}
Cells cannot be hidden or shown, must be added or removed. Override:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// add or remove items from data source, then
tableView.reloadData()
}

Related

UITableView: how stop selection while swipe the table view cell

I have swipe to delete code here and it my custom TableViewCell I have implemented setSelected method like below ..
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
// tableView.allowsSelectionDuringEditing = false
if tableView.indexPathForSelectedRow != nil, tableView.indexPathForSelectedRow == indexPath {
return UITableViewCell.EditingStyle.none
}
return UITableViewCell.EditingStyle.delete
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
//some code here
}
The logic will do tableview expand collapse based on selection ..but the problem here is if I swipe to delete setSelected also triggers.. not sure how to prevent that any help would be appreciated..
Try this in cellForRow
let cell = tableView.dequeueReusableCell(withIdentifier: "cell_identifier", for: indexPath)
cell.selectionStyle = UITableViewCell.SelectionStyle.none
//or this based on swift version
cell.selectionStyle = .none
return cell
I'm not sure what the appearance you are going for but this will produce the same effect.
If swipe is across the whole screen it will trigger the delete without button press.
If half swipe you can present buttons for user to choose options.
Half swipe (Shows options):
Full swipe (Triggers delete button):
Try adding these two tableView delegate methods for a swipe to delete
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Determine which rows should be editable
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath:
IndexPath) -> [UITableViewRowAction]? {
let button1 = UITableViewRowAction(style: .default, title: "Delete") {
action, indexPath in
print("delete pressed")
// Consider alert to confirm that it was intentionally deleted
}
button1.backgroundColor = UIColor.red
// Create any buttons you want
return [button1]
}
I tried it with and without your tableView method and it seemed to work fine both ways but I don't think your method is necessary if you choose this route
Hope this helps

tableView editing mode delete button (minus sign) not responding to tap - how do I fix this?

When my tableView goes into editing mode there's an icon on each side of my cell: the icon on the right is the default icon for rearranging the order of cells, and the icon on the left is the default icon for deleting a cell. I can easily interact with the rearranging icon with no problems, however, tapping on the delete icon gives no response. It only works when I do an awkward right swipe then left swipe on it. Below I've placed what I believe to be all the relevant code to my situation.
Some background information: I have three touch gestures in the view (a single tap, double tap, and long press). I've tried disabling them with conditions for when the editing mode is enabled. I've even tried deleting the touch gestures beforehand, but that didn't help. I thought it might be an auto layout issue that's not registering the area for the delete button, but the rearranging button works so shouldn't this? Both the my cell's leading and trailing constants are +10 to the view. Furthermore, isEditing is controlled by a UIButton. Finally, i have the tableView delegate set to self, and touch interaction when editing is enabled.
Any help would be appreciated. Thank you!
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if isEditing { return true }
return false
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if isEditing { return .delete }
return .none
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
countBeforeDeletingCell = dataSource.data.count
dataSource.data.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .none)
}
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = dataSource.data[sourceIndexPath.row]
dataSource.data.remove(at: sourceIndexPath.row)
dataSource.data.insert(movedObject, at: destinationIndexPath.row)
tableView.reloadData()
}
Hey If the you have use UITableViewController and using isEditing iOS defalut mode you have to override setEditing Mode and Changing Edit button Click.
iOS self.navigationItem.rightBarButtonItem = self.editButtonItem in editButtonItem is default UIViewController method. editButtonItem button Action override.
Swift Example:
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.reloadData()
}
it works for me on swift 5.7.May be you should config TrailingSwipeActionConfiguration like this:
unc tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive,
title: "Delete") { [weak self] _, _, complete in
//remove row in you data model here
tableView.deleteRows(at: [indexPath], with: .automatic)
complete(true)
}
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}

table view date selected only the long press

I'm using the tableViewCell in Xib.
In table view, didSelectRowAt function is only called when I long press the tableViewCell
My Code is below
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
categorytabelview.deselectRow(at: indexPath, animated: true)
self.categorylabel.text = totalArrayofCars.object(at: indexPath.row) as? String
categorytabelview.isHidden = true
}
I want to select the tabelViewCell data in single select not in long press.
Since you are using gesture, right before adding the gesture to view, add the following line
tap.cancelsTouchesInView = false // assuming tap is your gesture recogniser variable

In my UITableView, how can I reset the "selected cell color" back to default upon selection?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
checkRequirements() { () -> Void in
var room = self.rooms[indexPath.row]
self.roomForPreview = room
self.indexPathForPreview = indexPath
self.performSegueWithIdentifier(CONSTANTS.SegueLobbyToRoomPreview, sender: self.view)
}
}
I perform a segue when a user selects a cell, but when I unwind, I find that the cell still has a grey background.
How can I make the cell grey only on touch? Once the touch is gone, the cell goes back to normal color.
Use deselectRowAtIndexPath:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
...
If you're using a UITableViewController, you can set the clearsSelectionOnViewWillAppear property to true - this will work as well.

didSelectRowAtIndexPath not being called (Swift)

I've been going in circles for a while and nothing I've found in related posts seems to solve it.
I'm programmatically adding a table to a custom UIView. The table and row text displays correctly, but neither didSelectRowAtIndexPath nor willdSelectRowAtIndexPath fire when I run this on the simulator and try to click on any of the rows.
The relevant bits of my code below:
import UIKit
import AVFoundation
#IBDesignable
class PerformanceQuestionView: UIView, UITableViewDelegate, UITableViewDataSource {
var optionsTable = UITableView(frame: CGRectMake(10,200,250,200))
var optionItems = ["One", "Two", "Three", "Four"]
convenience init(rect: CGRect, performanceQuestion:PerformanceQuestion?) {
self.init(frame: rect)
NSLog("PerformanceQuestionView.init()")
self.optionsTable.dataSource = self
self.optionsTable.delegate = self
self.optionsTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.optionsTable.allowsSelection = true
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
NSLog("numberOfRowsInSection")
return optionItems.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
NSLog("cellForRowAtIndexPath")
var cell:UITableViewCell = self.optionsTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.optionItems[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, willSelectRowAtIndexPath indexPath: NSIndexPath!) -> NSIndexPath! {
NSLog("You will select cell #\(indexPath.row)!")
return indexPath
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
NSLog("You selected cell #\(indexPath.row)!")
}
override func layoutSubviews() {
super.layoutSubviews()
self.addSubview(optionsTable)
}
}
Removing the TapGestureRecognizer worked for me!!!
// var backgoroundTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
// self.view.addGestureRecognizer(backgoroundTap)
Reason for this could be, you are using a pan gesture in the view. like AAA mentioned removing your pan gesture will do the trick. But if you still want to use the pan gesture you could do the following
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false
Making cancelsTouchesInView, false will enable all you taps.
Remove the exclamation points:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
You need to add below code for Tap or Pan gesture.You need to tap.cancelsTouchesInView = false
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false
OR
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.mainBlurViewAction))
mainBlurView.addGestureRecognizer(gesture)
gesture.cancelsTouchesInView = false
Then it will work
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Call According requirement
}
I have the same problem long time, I am for thinking it's a bug in UITableView programmatically when creating a UIView class.
My temporary solution and although it is not a good idea, but it works. It is to place a button the size of the cell and have an action dispatched by a protocol, to achieve at least simulate this action.
It is not good practice but could not stay stuck there longer.
For Swift 3.0, you need to use this function exactly:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Input your code here
}
Look very closely to make sure you are using this function. The compiler won't complain if you have NSIndexPath or you don't have _ before tableView but it won't work. So use this function, put a breakpoint in and you will see it go to that point when you tap on a row.
I was testing this with a static table (all static content cells).
This was deprecated in Swift 3:
override func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
...
}
And replaced with:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
...
}
I tried all of the methods listed in this question and others. I finally deleted the table from my storyboard and started again.
In my storyboard, I added back the table, added a prototype cell. I connected the ViewController to the table. I connected the table to my dataSource and delegate methods.
I named the prototype identifier in the Attributes Inspector.
This worked for me. I did not apparently have any code to change.

Resources