I have some trouble with the appearance of my tableviews and cells on the iphone4s. Within the simulator and on new devices everything is fine.
UITableViewController
The custom table cell (picture 1) isn't presented correctly. All the labels etc. lie on top of each other. They should be shown one below the other like they do on the simulator.
ViewController with TableView
The other custom cells even don't show on the iPhone4s only a gray square appears.
I'm using Auto Layout. Do you have any suggestions?
Here's the code:
1st picture:
import UIKit
class FeedController: TableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// adjusting text size without quitting app
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "onContentSizeChange:",
name: UIContentSizeCategoryDidChangeNotification,
object: nil)
// set table row height
tableView.estimatedRowHeight = 89
tableView.rowHeight = UITableViewAutomaticDimension
// removes the back button after clicked on send button to write a post
self.navigationItem.hidesBackButton = true
// refresh control
self.refreshControl = UIRefreshControl()
self.refreshControl!.addTarget(self, action: Selector("refresh:"), forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl!.backgroundColor = UIColor.grayColor()
self.refreshControl!.tintColor = UIColor.whiteColor()
self.tableView.addSubview(refreshControl!)
}
func reloadFeed(note: NSNotification){
tableView.reloadData()
}
func refresh(sender: AnyObject){
self.refreshControl!.endRefreshing()
}
// called when the text size was changed by the user
func onContentSizeChange(notification: NSNotification) {
tableView.reloadData()
}
}
import Foundation
import UIKit
class TableViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, PDeliversStatusAlerts {
let notifCenter = NSNotificationCenter.defaultCenter()
override init() {
super.init()
notifCenter.addObserver(self, selector: "displayConnectionLostAlert", name: kConnectionLostNotification, object: self)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
notifCenter.addObserver(self, selector: "displayConnectionLostAlert", name: kConnectionLostNotification, object: self)
}
func displaySimpleAlert(#title:String, message:String){
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func displayModalDialog(#title: String, message: String, yesHandler: ((UIAlertAction!) -> Void)?, noHandler: ((UIAlertAction!) -> Void)?) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: yesHandler))
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: noHandler))
self.presentViewController(alert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func push(sender: AnyObject) {
}
//Tableview
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
2nd picture:
import UIKit
class NextViewController: ViewController, UITableViewDelegate, UITableViewDataSource{
var followedFeed : FollowedHashtagFeed?
var hottestFeed : HottestHashtagFeed?
var nearbyFeed : NearbyHashtagFeed?
var hashtagFeed : HashtagFeed?
#IBAction func hottestButtonTapped(sender:AnyObject) {
hashtagFeed = FeedFactory.instance().hottestHashtagFeed()
notifCenter.removeObserver(self)
notifCenter.addObserver(self, selector: "reloadFeed", name: hashtagFeed?.notificationName, object: nil)
hashtagFeed!.subscribe()
reloadFeed()
}
#IBAction func nearbyButtonTapped(sender: AnyObject) {
hashtagFeed = FeedFactory.instance().nearbyHashtagFeed()
notifCenter.removeObserver(self)
notifCenter.addObserver(self, selector: "reloadFeed", name: hashtagFeed?.notificationName, object: nil)
notifCenter.addObserver(self, selector: "didReceiveLocationPermissionNeededNotification:", name: "location_permission_needed", object: nil)
hashtagFeed!.subscribe()
reloadFeed()
}
#IBAction func followedButtonTapped(sender: AnyObject) {
hashtagFeed = FeedFactory.instance().followedHashtagFeed()
notifCenter.removeObserver(self)
notifCenter.addObserver(self, selector: "reloadFeed", name: hashtagFeed?.notificationName, object: nil)
hashtagFeed!.subscribe()
reloadFeed()
}
override func viewDidLoad() {
super.viewDidLoad()
//set table row height
tableView.rowHeight = UITableViewAutomaticDimension
//load feed cell
var nipName=UINib(nibName: "NextTableCell", bundle:nil)
self.tableView.registerNib(nipName, forCellReuseIdentifier: "nextCell")
followedButtonTapped(followedButton)
view.setNeedsLayout()
view.layoutIfNeeded()
println("Frame Height:")
println(tableView.frame.height)
println(tableView.bounds.height)
println("Frame Width:")
println(self.tableView.frame.width)
println(self.tableView.bounds.width)
/*
hashtagFeed = FeedFactory.instance().followedHashtagFeed()
//subscribe to feed changes
notifCenter.addObserver(self, selector: "reloadFeed", name: hashtagFeed?.notificationName, object: nil)
hashtagFeed!.subscribe()*/
}
func didReceiveLocationPermissionNeededNotification(note: NSNotification){
displayModalDialog(
title: "Location Permission Needed",
message: "In order to use this functionality the app needs your permission to use location data - do you want to give this permission now?",
yesHandler: {
(action: UIAlertAction!) in LocationHelper.instance().askForPermission()
},
noHandler: nil
)
}
//Tableview
func reloadFeed(){
tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hashtagFeed!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nextCell", forIndexPath: indexPath) as NextTableCell
let hashtag = hashtagFeed!.toArray()[indexPath.row]
cell.loadItem(hashtag)
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
}
}
This sort of issue can present itself when the constraints set up for the cell's subviews do not enforce a specific height for the cell.
For example, if you have a cell that contains a single subview, and the subview has top/bottom/left/right constraints to its superview (nearest neighbor, i.e. the cell's contentView) of 10px, but the subview itself does not have a height constraint, the cell will not be laid out properly.
This can look like all cells on top of one another, or all cells presented with the default 44px height.
To fix the issue (if we're working with the example view hierarchy of a cell with a single subview), define a height constraint for the subview. You might also need to set the height constraint's priority to something less than 1000.
Not sure if this will fix your specific issue, but it's fixed similar issues for me, so presenting it here as an option.
For what it's worth, I'm fairly certain that your issue is constraints-related, which means the code above wont really help answer the question.
Related
Swift
As you can see in this swift code I am trying to create a table view for my logout controller. However, I am facing problems with the "log out" button showing as a cell in my view controller. I don't know what the problem is because it builds without any errors and I have gone and checked several times but can't find the problem.
import UIKit
struct SettingsCellModel {
let title: String
let handler: (() -> Void)
}
final class SettingsViewController: UIViewController {
private var tableView: UITableView {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}
private var data = [[SettingsCellModel]]()
override func viewDidLoad() {
super.viewDidLoad()
configureModels()
view.backgroundColor = .systemBackground
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
private func configureModels() {
let section = [SettingsCellModel(title: "Log Out") { [weak self] in
self?.didTapLogOutButton()
}
]
data.append(section)
}
private func didTapLogOutButton() {
let actionSheet = UIAlertController(title: "Log Out", message: "Are you sure you want to log out", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Log Out", style: .destructive, handler: { _ in
logOut (completion: { success in
DispatchQueue.main.async {
if success {
//present log in
let loginVC = LoginViewController()
loginVC.modalPresentationStyle = .fullScreen
self.present(loginVC, animated: true) {
self.navigationController?.popToRootViewController(animated: false)
self.tabBarController?.selectedIndex = 0
}
}
else {
//error occurred
fatalError("Could not log out user")
}
}
})
}))
actionSheet.popoverPresentationController?.sourceView = tableView
actionSheet.popoverPresentationController?.sourceRect = tableView.bounds
present(actionSheet, animated: true)
}
}
extension SettingsViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.section][indexPath.row].title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
data[indexPath.section][indexPath.row].handler()
}
}
Issue is you are using Computed property private var tableView: UITableView { that means every time you access tableView in your code its closure is executed (or its value is evaluated), and because you instantiate a new instance of tableView in its closure you receive different instances of tableView in all the 3 statements
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
hence tableView instance you added as subView is different from the one that has delegate and data source set as self.
What you need
Option 1:
private var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
Option 2: (Preferred)
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
Hope it helps
I am trying to call a UIAlertController from within my UITtableViewCell when my function is called. It gives me an error saying present is not available. I understand it's not within a ViewController. I am looking for an approach to access it.
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapGestureShareImageView = UITapGestureRecognizer(target: self, action: #selector(self.shareImageTouchUpInside))
shareImageView.addGestureRecognizer(tapGestureShareImageView)
shareImageView.isUserInteractionEnabled = true
}
#objc func shareImageTouchUpInside() {
showAction()
}
func showAction() {
let alertController = UIAlertController(title: "Action Sheet", message: "What do you like to do", preferredStyle: .alert)
let okButton = UIAlertAction(title: "Done", style: .default, handler: { (action) -> Void in
print("Ok button tapped")
})
let deleteButton = UIAlertAction(title: "Skip", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
alertController.addAction(okButton)
alertController.addAction(deleteButton)
present(alertController, animated: true, completion: nil)
}
You can try to use delegate
protocol AlertShower{
func showAlert(TableCustomCell)
}
class TableCustomCell: UITableViewCell {
var delegate: AlertShower?
#IBAction func showClicked(_ sender: UIButton) {
self.delegate?.alertShower(sender:self)
}
}
in the VC
class viewController: UIViewController, AlertShower {
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = areaSettTable.dequeueReusableCell(withIdentifier:CellIdentifier1) as! TableCustomCell
cell.delegate = self
return cell
}
func showAlert(sender:TableCustomCell) {
// show alert here
}
}
Present is only available to ViewControllers. You are going to have to redirect the touch event to your view controller. The most common way of doing this would be having a delegate property in your UITableViewCell.
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276
I ran into a similar problem myself when creating a custom activity indicator from a subclassed UIView. What I did was create the 'show' function (in the subclass) and pass in a UIViewController parameter, like so:
public func play(inView view: UIViewController) {
//Perform action here
view.present(alertController, animated: true, completion: nil)
}
Simply call it in your view controller like so:
CustomClass.play(inView: self)
Hopefully this helps!
I have a tableview with buttons, and I would like to create a UIActionSheet here when I click on the 3 dots button. It is a custome tableview cell.
My UITableViewCell:
import UIKit
class UserTableViewCell: UITableViewCell {
#IBOutlet weak var nameLabel: 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
}
func view(with user: User){
nameLabel.text = user.getName();
}
#IBAction func btnMenu(_ sender: UIButton) {
//here I want to execute the UIActionSheet
}
#IBAction func btnDial(_ sender: UIButton) {
}
}
and in my view controller:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as? UserTableViewCell;
cell?.view(with: users[indexPath.row]);
return cell!;
}
Try this and do some changes in UserTableViewCell
class UserTableViewCell: UITableViewCell {
weak var myVC : UIViewController?
#IBAction func btnMenu(_ sender: UIButton) {
//here I want to execute the UIActionSheet
let actionsheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
actionsheet.addAction(UIAlertAction(title: "Take a Photo", style: UIAlertActionStyle.default, handler: { (action) -> Void in
}))
actionsheet.addAction(UIAlertAction(title: "Choose Exisiting Photo", style: UIAlertActionStyle.default, handler: { (action) -> Void in
}))
actionsheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (action) -> Void in
}))
myVC?.present(actionsheet, animated: true, completion: nil)
}
}
And modify this method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as? UserTableViewCell;
cell?.view(with: users[indexPath.row]);
cell?.myVC = self
return cell!;
}
make outlets of button in cell class
then in tableView where you are using this cell write the code below in cellForRowAtIndexPath
cell.yourButton.addTarget(self, action: #selector(yourButtonTapped), for: .touchDown)
and now in your yourButtonTapped method write actionSheet code following the link :
UIActionSheet iOS Swift
hope its help
Closure Approach
1 - Declare your actionBlock in your UserTableViewCell
var actionClosure : (()->Void)? = nil
2 - Execute your action block in your Cell Action
#IBAction func btnMenu(_ sender: UIButton) {
//here I want to execute the UIActionSheet
self.actionClosure?()
}
3 - Setup your cell block action adjusting your cellForRowAtIndexPath method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserTableViewCell", for: indexPath) as! UserTableViewCell
cell.actionClosure = { [weak self] in
//SHow your ActionSheet Here
}
return cell
}
Full Code
CellForRow implementation
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserTableViewCell", for: indexPath) as! UserTableViewCell
cell.actionClosure = { [weak self] in
//SHow your ActionSheet Here
}
return cell
}
TableView Cell
import UIKit
class UserTableViewCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel!
var actionClosure : (()->Void)? = nil
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
}
func view(with user: User){
nameLabel.text = user.getName();
}
#IBAction func btnMenu(_ sender: UIButton) {
//here I want to execute the UIActionSheet
self.actionClosure?()
}
#IBAction func btnDial(_ sender: UIButton) {
}
}
just add onMenubtnClick method in your ViewControler instead of cell.
add this in your cellForRowAt method
cell.youtBtn.addTarget(self, action: #selector(self.btnMenu(_:)), for: .touchUpInside)
add this code in your ViewController
#IBAction func btnMenu(_ sender: UIButton) {
//here I want to execute the UIActionSheet
}
I am using table view in my Swift project. The problem is with table view cell index path value. When the table gets loaded initially, the index values are ok. But as soon as I scroll my table view the cell index paths change and the ids I get from a data array are wrong. Googling results that it is because of reusable cell like thing. Here's my view controller code:
//
// ProjectsController.swift
// PMUtilityTool
//
// Created by Muhammad Ali on 9/23/16.
// Copyright © 2016 Genetech Solutions. All rights reserved.
//
import UIKit
class ProjectsController: UIViewController {
//MARK: Properties
var ProjectsArray: Array<Project> = []
#IBOutlet weak var ProjectsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBarHidden = true
// Remove indenting of cell
if self.ProjectsTableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.ProjectsTableView.separatorInset = UIEdgeInsetsZero
}
if self.ProjectsTableView.respondsToSelector(Selector("setLayoutMargins:")) {
self.ProjectsTableView.layoutMargins = UIEdgeInsetsZero
}
self.ProjectsTableView.layoutIfNeeded()
// Get projects
getProjects()
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - TableView Datasource
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.ProjectsArray.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// print("clicked")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> ProjectTableViewCell {
print(indexPath.row)
let cell = tableView.dequeueReusableCellWithIdentifier("ProjectViewCell", forIndexPath:indexPath) as! ProjectTableViewCell
// Remove indenting of cell
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
// Set project name
cell.ProjectName.text = "\((indexPath.row)+1). \(self.ProjectsArray[indexPath.row].ProjectName)"
// Set action button
cell.ActionButton.tag = indexPath.row
cell.ActionButton.addTarget(self, action: #selector(ProjectsController.projectActions(_:)), forControlEvents: .TouchUpInside)
return cell
}
func reloadTableViewAfterDelay()
{
ProjectsTableView.performSelector(#selector(UITableView.reloadData), withObject: nil, afterDelay: 0.1)
}
#IBAction func projectActions(sender: UIButton) {
let index = sender.tag
let optionMenu = UIAlertController(title: nil, message: self.ProjectsArray[index].ProjectName, preferredStyle: .ActionSheet)
// Report Progress
let reportProgressAction = UIAlertAction(title: "Report Progress", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.performSegueWithIdentifier("ShowReportProgress", sender: sender)
})
// Cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
optionMenu.addAction(reportProgressAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let button = sender where segue.identifier == "ShowReportProgress" {
let upcoming: ReportProgressController = segue.destinationViewController as! ReportProgressController
print(self.ProjectsArray[button.tag].ProjectId)
upcoming.ProjectId = self.ProjectsArray[button.tag].ProjectId
upcoming.ProjectName = self.ProjectsArray[button.tag].ProjectName
}
}
// MARK: Get Projects Function
func getProjects() -> Void
{
var params = Dictionary<String,AnyObject>()
params = ["user_id":CFunctions.getSession("id")]
WebServiceController.getAllProjects(params){ (type, response, message) -> Void in
if (type == ResponseType.kResponseTypeFail)
{
// Show Error
let alert = UIAlertController(title: "Error(s)", message:"Unable to load projects.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
else
{
//debugPrint(response)
if(response.count>0)
{
self.ProjectsArray = response
}
else
{
// Show Error
let alert = UIAlertController(title: "Error(s)", message:"No projects found.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
self.reloadTableViewAfterDelay()
}
}
}
}
I want each cell's index value to be intact whether I scroll down or up.
In your iPhone screen, for example you can see 5 cells at a time.
So, first time, when you load tableView cellForRowAtindexPAth method will be called for first 5
cells.
"As you mentioned, first time you are loading and tableView indexes
are correct."
Now when you scroll down, cellForRowAtIndexPath method will be called
for only 6 and 7.
"Till this time everything works ok, as you mentioned. AS you can see overall indexpath as intact 1,2, 3,4,5,6,7."
*Dark cells are currently visible on your screen.
Now when you scroll up {2 cells}. Now you can see the current visible cell's on your screen are 1,2,3,4,5.
Here, cellForRowAtIndexPath method will be called for ONLY cells numbered 2,1.
Because cell numbers 3,4,5 are already loaded/visible in your screen.
So, your Print log will be 1,2,3,4,5,6,7,2,1.
You should add UITableViewDelegate and UITableViewDataSource to your class. and set it ProjectsTableView.delegate = self in viewDidLoad.
You need to get indexPath of button using tableViewCell's hierarchy.
#IBAction func projectActions(sender: UIButton) {
let button = sender as! UIButton
let view = button.superview!
let cell = view.superview as! UITableViewCell
let indexPath = self.reloadTableViewAfterDelay.indexPathForCell(cell)
let index = indexPath.row
}
if let button = sender where segue.identifier == "ShowReportProgress" {
let upcoming: ReportProgressController = segue.destinationViewController as! ReportProgressController
let view = button.superview!
let cell = view.superview as! UITableViewCell
let indexPath = self.reloadTableViewAfterDelay.indexPathForCell(cell)
let index = indexPath.row
print(self.ProjectsArray[index].ProjectId)
upcoming.ProjectId = self.ProjectsArray[index].ProjectId
upcoming.ProjectName = self.ProjectsArray[index].ProjectName
}
Need to get indexPath of button using tableViewCell's than used below code
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellId: NSString = "Cell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId as String)! as UITableViewCell
let ActionButton : UIButton = cell.viewWithTag(10) as! UIButton
ActionButton.addTarget(self, action: #selector(ViewController.projectActions(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
#IBAction func projectActions(sender: UIButton) {
let buttonPosition = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(buttonPosition)
print(indexPath?.row)
}
I have an issue that prevents me from display the input from the alert message into the table view. There are no errors but I don't know what's the real problem that makes the table empty.
import UIKit
import Parse
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
#IBOutlet weak var childTbl: UITableView!
var names=[String] ()
override func viewDidLoad() {
super.viewDidLoad()
self.childTbl.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
#IBAction func Addchild(sender: AnyObject) {
var alert=UIAlertController(title: "",
message: "إضافة طفل جديد",
preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler({(textField) -> Void in
textField.text=""
})
alert.addAction((UIAlertAction(title: "حفظ", style: .Default, handler: { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
if let textField = alert.textFields!.first as?UITextField{
self.names.append(textField.text)
println(self.names)
}
})))
alert.addAction((UIAlertAction(title: "إلغاء", style: .Default, handler: { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
//to display the alert
presentViewController(alert,
animated: true,
completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//UITabledatasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.names.count;
}
//function to creat a cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = self.childTbl.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = self.names[indexPath.row]
return cell
}
}