Search Your Question

Showing posts with label TableView. Show all posts
Showing posts with label TableView. Show all posts

I have 100 cells. In each cell I have 5 button. How can I check which cell button is clicked?

Ans : 

There are various approach for this problem. But following two approach are better.

Approach-1 : Delegate - Protocol 

Cell : 

protocol CellSubclassDelegate: class {
    func buttonTapped(cell: CellSubclass)
}

class CellSubclass: UITableViewCell {

@IBOutlet var someButton: UIButton!

weak var delegate: CellSubclassDelegate?

override func prepareForReuse() {
    super.prepareForReuse()
    self.delegate = nil
}

@IBAction func someButtonTapped(sender: UIButton) {
    self.delegate?.buttonTapped(self)

}

ViewController:

class MyViewController: UIViewController, CellSubclassDelegate {

    @IBOutlet var tableview: UITableView!

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellSubclass

        cell.delegate = self


    }

    func buttonTapped(cell: CellSubclass) {
        guard let indexPath = self.tableView.indexPathForCell(cell) else {
            // Note, this shouldn't happen - how did the user tap on a button that wasn't on screen?
            return
        }

        //  Do whatever you need to do with the indexPath

        print("Button tapped on row \(indexPath.row)")
    }


Approach-2 Using Closure:

Cell :

class MyCell: UITableViewCell {
    var button: UIButton!

    var buttonAction: ((Any) -> Void)?

    @objc func buttonPressed(sender: Any) {
        self.buttonAction?(sender)
    }

}


ViewController : 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! MyCell
    cell.buttonAction = { sender in
        // Do whatever you want from your button here.
    }
    // OR
    cell.buttonAction = buttonPressed(closure: buttonAction, indexPath: indexPath) // <- Method on the view controller to handle button presses.

}

No need to explain code. Simple as that.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!


How To declare custom tableview cell? What Is The Use Of dequeuereusablecellwithidentifier ?

Ans : 

Let's create custom cell :

1. Take viewcontroller or tableviewcontroller
2. In Tableview, put one uitableviewcell and change style to custom.
3. Give any string (i.e "newcell") to reuseidentifier of cell in attribute inspector.
4. Put labels, textfields, views in cell according to your need.
5. Add new file named as newCell.swift that inherit from UITableViewCell.
6. Select your cell and give class name newCell.
7. Now you can make outlet of that cell in newCell.swift.

Here magic will be created using dequeuereusablecellwithidentifier : 

The best part of using dequeueReusableCellWithIdentifier is that using this you can re-use your cells.

Imagine if your table has 1000 entries. Now, if for each entry a table cell would be created then for 1000 entries, 1000 tableview cells and memory allocation for 1000 tableview cells.

App will be slowed down or would crash if the entries goes beyond 1000.

When we use, dequeueReusableCellWithIdentifier, the tableView just creates exactly the number of cells based on your table height and cell height. Suppose, if it shows 4 cells in the tabelView and rest you can see by scrolling, then memory for only 4 cells would be allocated at any given point of time.

Now, when you will scroll the tableView, it will re-use the same cell but will change the cell content (data) based on your data source.

Hope this clears your doubt.

Code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:"newcell"];
    cell.textLabel.text = @"Test";
    return cell;

}

Why tableview cell separator leave some space before?

Ans : 




Alternatively, you can also edit this in interface builder (IB):
  1. Go to IB.
  2. Select Table View.
  3. Open "Attribute Inspector" on the right.
  4. Change "Separator Insets" from Default to Custom.
  5. Change the "Left" attribute from 15 to 0.
15 is default. So Left side space is seen before cell seperator.

Expandable tableview Logic in iOS

Ans : 

Logic  : 

  • Display UITableView containing just the header/section titles for each category.
  • When a section is touched, expand it if it is not already expanded. Otherwise, collapse the section.
  • When a section is touched, expand it and if another section is currently expanded collapse that section so that only one section is expanded at a time.
  • To expand a section, determine the number of items that must be displayed within that section and insert that number of rows in the UITableView; then display the items in the newly inserted rows.
  • To collapse a section, determine the number of items currently displayed within that section and delete that number of rows from the UITableView.

To reload one section only : 

[self.tableView beginUpdates];
 (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation:
[self.tableView endUpdates];

UITableviewDelegate and UITableViewDataSource Methods

Ans : 

UITableview's Delegate Methods :


The UIViewController in which UITableView you use must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

Configuring Rows for the Table View

- tableView:heightForRowAtIndexPath:
- tableView:indentationLevelForRowAtIndexPath:
- tableView:willDisplayCell:forRowAtIndexPath:

Managing Accessory Views

- tableView:accessoryButtonTappedForRowWithIndexPath:
- tableView:accessoryTypeForRowWithIndexPath: Deprecated in iOS 3.0

Managing Selections

- tableView:willSelectRowAtIndexPath:
- tableView:didSelectRowAtIndexPath:
- tableView:willDeselectRowAtIndexPath:
- tableView:didDeselectRowAtIndexPath:

Modifying the Header and Footer of Sections

- tableView:viewForHeaderInSection:
- tableView:viewForFooterInSection:
- tableView:heightForHeaderInSection:
- tableView:heightForFooterInSection:

Editing Table Rows

- tableView:willBeginEditingRowAtIndexPath:
- tableView:didEndEditingRowAtIndexPath:
- tableView:editingStyleForRowAtIndexPath:
- tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
- tableView:shouldIndentWhileEditingRowAtIndexPath:

Reordering Table Rows

- tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

Copying and Pasting Row Content

- tableView:shouldShowMenuForRowAtIndexPath:
- tableView:canPerformAction:forRowAtIndexPath:withSender:
- tableView:performAction:forRowAtIndexPath:withSender: 








UITableview's Data Source Methods : The NSTableViewDataSource protocol declares the methods that an instance of NSTableView that provides the data to a table view and allows editing of the contents of its data source object.

All the methods are described in the following.

Getting Values

- numberOfRowsInTableView: (Required)
- numberOfSectionInTableView:
- cellForRowAtIndexPath : (Required)
- tableView:objectValueForTableColumn:row:

Setting Values

- tableView:setObjectValue:forTableColumn:row:

Implementing Pasteboard Support

- tableView:pasteboardWriterForRow:

Drag and Drop

- tableView:acceptDrop:row:dropOperation:
- tableView:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:
- tableView:validateDrop:proposedRow:proposedDropOperation:
- tableView:writeRowsWithIndexes:toPasteboard:
- tableView:draggingSession:willBeginAtPoint:forRowIndexes:
- tableView:updateDraggingItemsForDrag:
- tableView:draggingSession:endedAtPoint:operation:

Sorting

- tableView:sortDescriptorsDidChange:

Tips : UITableViewDelegate has no any required methods.

Dynamically set UITableview cell height

Ans : 

For auto cell height in tableview in Swift 3.0

Write following 2 lines of code in viewDidLoad and before reload tableview :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

Following steps must to do otherwise label height will not be increase and so UITableiViewCell.

Label height must be auto incremented using numberOfLines = 0

LineBreak should be set according your need word-wrap, char-wrap, etc...

UITableview and UICollectionview

Similarity :
The way to setup both with cell registration, dequeing cells, specifying size and heights are pretty much the same.

Diffrence :
1. The collection view is much more robust in terms of layout features and other things like animations.
Tableiw is a simple list, which displays single-dimensional rows of data. It’s smooth because of cell reuse and other magic.

2. UICollectionView is the model for displaying multidimensional data . 
UITableViewhas a couple of styles of cells stacked one over the other. You should not try to bend it to do any other kind of things too much complex than that kind of layout.

3. UICollectionView is a much more powerful set of classes that allow modifying almost every aspect of how your data will appear on the screen, especially its layout but also other things.

Advantage of Collectionview :
The biggest advantage of using collection view is the ability to scroll horizontally.
 If you want multiple columns in your apps then UICollectionView is the best way to do it. 


It is possible to have multiple columns in table view as well but it gets really messy since you are dealing with and array to display data in a table view.

UICollectionView Supports complex layouts. Apple provides you with something called UICollectionViewDelegateFlowLayout which provides you the flow of left and right as well as up and down.

UICollectionView supports custom animations based on different layouts which again cannot be done in UITableView.

Disadvantage of Collectionview (Advantage of Tablvieview over) :

Major disadvantages of using UICollectionView is auto sizing of your cells. It takes a lot of trial and error to get auto sizing to work correctly. UITableView wins here as all you have to do is return UITableView automatic dimensions for the height of your row in each one of your cells.

Summary :
If you need more control over your layout, go with UICollectionView, If you need simple list go with UITableview.