UIButton not appearing on UITableViewCell - ios

Alright, I am testing around a bit with core data, something I recently have started to discover, basically, what i have so far, is a single view app, that has a data source, and i can press a button and it brings up and alert, which from there i can add names to the list, and delete names from the list, i can close my app and still maintain my data. here is the issue/question, i am trying to do an update, so i can edit names in the list, i have a uibutton set up on my prototype cell, and i have it linked to my viewController, and have a function set inside the IBAction for the button. however, the button does not appear in my sim at run time.
here i have some code.
this is code for the edit button, and its function:
#IBAction func editButton(sender: AnyObject) {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 2
let alert = UIAlertController(title: "Update",
message: "Please enter the new name.",
preferredStyle: .Alert)
// 3
let updateAction = UIAlertAction(title: "Save",
style: .Default){(_) in
let nameTextField = alert.textFields![0]
self.updateName(indexPath.row, newName: nameTextField.text!)
self.tableView.reloadData()
}
// 4
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(updateAction)
alert.addAction(cancelAction)
// 5
self.presentViewController(alert, animated: true, completion: nil)
}
here is my cellForRowAtIndexPath func
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
let people = peoples[indexPath.row]
cell.textLabel!.text = people.name
return cell
}
here is an image of my storyboard
Storyboard
if you need further information or code, please let me know and i will provide it.

Related

UITableViewCell Content Disappears

I have a uiTableView with 3 cells that have a uiContextualAction implemented through the trailingSwipeActionsConfigurationForRowAt delegate method.
On tap of the uiContextualAction I display an actionSheet with two actions - delete and dismiss.
When the actionSheet is displayed without having pressed any action, the cell's content for all 3 cells, specifically a uiImageView suddenly disappears.
Is there something inherent to uiTableViews causing this? I placed breakpoints throughout the aforementioned flow but to no avail on how to remedy this. Any thoughts would be appreciated.
BEFORE presented actionSheet - ImageView (red background w/ blue gradient image) of UITableViewCell
AFTER on presented actionSheet - ImageView (red background w/o blue gradient image)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .normal, title: "") { (action, view, completion) in
self.onDeleteCell(indexPath)
completion(true)
}
delete.backgroundColor = UIColor.red
delete.image = #imageLiteral(resourceName: "x_circle")
let config = UISwipeActionsConfiguration(actions: [delete])
config.performsFirstActionWithFullSwipe = false
return config
}
func onDelete(_ indexPath: IndexPath) {
AlertController.showActionSheet(self, title: nil, message: nil, actionOneTitle: "Delete", actionOneStyle: .destructive, actionTwoTitle: "Dismiss", actionTwoStyle: .cancel) { (_) in
self.updateCells(indexPath)
}
}
//From custom AlertController class
static func showActionSheet(_ inViewController: UIViewController, title: String?, message: String?, actionOneTitle: String, actionOneStyle: UIAlertAction.Style, actionTwoTitle: String, actionTwoStyle: UIAlertAction.Style, actionOneHandler: #escaping ((UIAlertAction) -> Void)) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let actionOne = UIAlertAction(title: actionOneTitle, style: actionOneStyle, handler: actionOneHandler)
alert.addAction(actionOne)
let actionTwo = UIAlertAction(title: actionTwoTitle, style: actionTwoStyle, handler: nil)
alert.addAction(actionTwo)
inViewController.present(alert, animated: true, completion: nil)
}
Still unsure what the issue is/was...but I replaced the vector image as png and it appears to render and not suddenly vanish anymore..
Not a definitive solution, but it for now happens to work for me.

How can I create tableView in alertView with default values?

My code is this:
let alrController = UIAlertController(title: "Membri", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
tableView.backgroundColor = UIColor.white
alrController.view.addSubview(tableView)
let cancelAction = UIAlertAction(title: "Esci", style: UIAlertActionStyle.cancel, handler: {(alert: UIAlertAction!) in})
alrController.addAction(cancelAction)
self.present(alrController, animated: true, completion:{})
I want to populate (but I don't know how) the tableView with this values in my array: names["name1","name2","name3"]
Can someone help me?
To populate an action sheet, you don't add a tableView. Instead, you simply add the actions and it will create and manage the tableView privately.
For a recent tutorial, see UIAlertController Examples
The idea is that you'd create an UIAlertAction for each String in your array, including a closure for what to do when user taps that action row.
for name in names
{
let namedAction = UIAlertAction(title: name, style: .default)
{ (action) in
// do something when this action is chosen (tapped)
}
alrController.addAction(namedAction)
}
You need to implement the following tableView dataSource methods in order to populate this data and also set tableView datasource to alertController like below:-
tableView.dataSource = alertController
TableView DataSource method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: yourCustomCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? yourCustomCell
else {
fatalError("yourCustomCell not found")
}
cell.textLabel.text = names[indexpath.row]
return cell
You can use custom UIViewController transition to achieve this kind of functionality.
This link: https://github.com/pgpt10/Custom-Animator will give you an idea of how you can achieve that.

iOS - UITableViewCell, UIAlertController

Good day to all. Faced a problem. I need to make a table with a button and by clicking on the button I get a alert with the number of the cell. The table cells themselves are not active. That's how I realized it. When I scroll the table in the beginning everything is fine, when you press the button, a alert is displayed with the correct line number, but after 4 elements an error appears.
This error appears in the line where I'm working with the 4 tag.
Fatal error: unexpectedly found nil while unwrapping an Optional value
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell
if (tableView.tag == 1) {
let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel
numLabel.text = String(indexPath.row)
} else if (tableView.tag == 2) {
//Error appears here
let numButton: UIButton = tableView.viewWithTag(4) as! UIButton
numButton.setTitle(String(indexPath.row), for: .normal)
numButton.tag = indexPath.row
}
return cell
}
#IBAction func showAlertForRow(row: UIButton) {
let alert = UIAlertController(title:"Test work",message:"Cell at row \(row.tag) was tapped!",preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
What you are designing for implementing this procedure is not correct. What you can do
Make a custom cell
Add a button in custom cell
Add action in that button in CellForRowAtIndexPath
Handle action from ViewController where you added tableView.
I made a whole project for you.Just to let you know. if you want to add customCell in tableView you need to register it like this in viewDidLoad.
i have done is in ViewController.swift file. check out my project.
let nib = UINib.init(nibName:String(describing: sampleTableViewCell.self) , bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "chatCell")
Then check cellForRowAtIndexPath function:
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell
cell.clickMeBtn.tag = indexPath.row
cell.clickMeBtn.addTarget(self, action: #selector(onButtonPressed(sender :)), for: .touchUpInside)
return cell
}
Button press function:
func onButtonPressed(sender:UIButton) {
let alert = UIAlertController.init(title:"Cell index is"+String(sender.tag), message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction.init(title: "ok", style: UIAlertActionStyle.default) { (UIAlertAction) in
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
Check only three files:
Github link
ViewController.swift
sampleTableViewCell.swift
sampleTableViewCell.xib**
Here is the output:

How to fetch data displayed in a TableView cell and display it in a textfield?

I have a tableView in a view controller where I display data from an API call, now if the user selects a tableview cell(say row 2 in the TableView), I want to fetch that data(Data in row 2 of TableView) and display it in the Textfield on the same screen. What is the best way to do this?
The simplest way is you can show show the UIAlertController with textField on didSelect of tableViewCell.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Edit Data", message: "Edit corresponding detail", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Enter name"
textField.text = yourArray[indexPath.row]
}
alert.addAction(UIAlertAction(title: "Edit", style: .default, handler: { (action) in
//Edit data on array
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
You can try this one, When user select's particular UITableViewCell then that cell contents will be show in UITextField.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell= tableView1.cellForRow(at: indexPath)
if let txtVal = cell?.textLabel?.text {
textField.text = txtVal
}
}
You have data from from webservice which you are displaying on your UITableview say arrWebServiceData. and you have index of row where user clicked on say index. Simplest way is to get Data from arrWebServiceData at index and use it to display on test field.
for example:
NSArray *arrWebServiceData; //you are storing data from Wevserice here.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let index = indexPath.row;
let dataAtIselectedIndex = yourArray[indexPath.row] ;
//If data is string, dirctly display it on text field,or if its dictionary, set object of diction on your text field.
}

Swift How to get access func from UITableViewRowAction

I'm a beginner of Swift, and I searched a lot of stuffs, but couldn't figure out and decided to post my first question ever here.
I have a table view to show tweets by using twitter fabric and I use UITableViewRowAction to present two options to users when a swipe is done on a row, "funnelOne" and "funnelTwo", to categorize their tweets by adding tags to each tweet.
In the view controller, I add two functions to make an alert and get a value of 'funnelTag' to store it to my core data.
However, I am not sure if I can correctly store the number to the core data because somehow different cell would be deleted if I push one of swipeable buttons. I know I can write a code within 'func tableView' to delete the row, but how I can get access from out of 'func tableView' to delete the row successfully??
If it can be resolved, I should be able to successfully store the value to my core data.
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) as? CustomTableViewCell
let funnelOne = UITableViewRowAction(style: .Default, title: "funnel") {
(action, indexPath) -> Void in
funnelTag = 1 // funnelTag is Int I want to store in my Core Data
cell!.tag = funnelTag
// self.tweets.removeAtIndex(indexPath.row) - I know this is working
tableView.setEditing(false, animated: true)
}
let funnelTwo = UITableViewRowAction(style: .Default, title: "funnel") {
(action, indexPath) -> Void in
funnelTag = 2
cell!.tag = funnelTag
tableView.setEditing(false, animated: true)
// self.tweets.removeAtIndex(indexPath.row)
}
These are two functions I add. if I implement these functions, top row would be deleted even though I want to delete other row... the first function, funnelTweet() is properly working, but the second function does not seem to work correctly..
func funnelTweet(cell: CustomTableViewCell){
let index: Int = cell.tag
if SettingStore.sharedInstance.isNoAlert(){
self.submitFunnel(index, cell: cell)
} else {
self.alert = UIAlertController(title: NSLocalizedString("stock_confirm_funnel", comment: ""), message: nil, preferredStyle: .Alert)
self.alert!.addAction(UIAlertAction(title: NSLocalizedString("common_ok", comment: ""), style: .Destructive) { action in
self.submitFunnel(index, cell: cell)
})
self.alert!.addAction(UIAlertAction(title: NSLocalizedString("common_cancel", comment: ""), style: .Cancel) { action in
cell.moveToLeft()
})
self.presentViewController(self.alert!, animated: true, completion: nil)
}
}
func submitFunnel(index: Int, cell: CustomTableViewCell){
var tweet = self.tweets[index]
// store to local storage
TagStore.sharedInstance.saveData(tweet.createdAt, funnelTag: funnelTag, id: tweet.tweetID)
self.tweets.removeAtIndex(index)
self.tableView!.reloadData()
}
Thank you for your help!
In the Second function you have not initialized the index before using it.
func submitFunnel(index: Int, cell: CustomTableViewCell){
// Initialize index here before using it in the next statement.. that is give it a value, otherwise it will return nil
var tweet = self.tweets[index]
// store to local storage
TagStore.sharedInstance.saveData(tweet.createdAt, funnelTag: funnelTag, id: tweet.tweetID)
self.tweets.removeAtIndex(index)
self.tableView!.reloadData()
}

Resources