Showing posts with label UITableViewCell. Show all posts
Showing posts with label UITableViewCell. Show all posts

Thursday, October 3, 2019

Custom cell class datasource in MVVM design pattern



We generally pass a model to cell to configure/render and the reason behind it is, instead of passing multiple parameters, we can have a model to be passed as parameter.


Let’s take a below cell for example which is having 4 labels and in MVVM design pattern, viewmodels build and gives model to cell in cellForRowAt in viewcontroller.





This seems/sounds familiar as this is what we have been doing.
But, there are flaws in this approach.

  1. What If I want to reuse the cell?
  2. In MVVM design pattern view(in this case cell) should not hold a model(Agree?)



I can not reuse the cell efficiently as this cell is tightly coupled with a model.

First in place, this poor cell is having 4 labels and technically needs 4 stings to display. As simple as that. Isn’t it?

Then why to pass a model and create a tight coupling.

Instead of passing a model, Cell can have a datasource implemented like below.




Now cell configuration happens based on the ProductCellDataSource protocol. That means any model that confirms to this protocol can be passed to cell configure method to render the cell.




In other words, cell is just asking to send me the data as per my protocol and it is saying I am not literally worried about the model you are sending as long as it confirms to my datasource protocol.




With this approach, cell will not have any tight coupling with models(MVVM basic rule) and it can be reused by passing any model which confirms to it’s datasource protocol.

Hope this post is useful. Feel free to comment incase of any queries.


Saturday, December 30, 2017

UITableView Scrolling issue for cells having UITextField/UITextView as subviews

Recently, I have faced UITableView scrolling issue If Cells are having editable UITextField/UITextView as subviews.
Just wanted to let everyone know the fix I have found for this in this post.





Check the Content Touch check boxes for both UITextView in the Cells and for UITableView and make sure both the checkboxes are checked.


UITextView










UITableView





Now the table view should be scrollable 😃



Not pretty sure what are those checkboxes are doing and what is happening there, But this saved my day. 
I will update the post as soon as I get what is happening over there.


Hope this post is useful. Feel free to comment incase of any queries.


Saturday, November 19, 2016

Swift 3 UITableView Dynamic cell height based on content

Let’s take an example of chat application, where chat bubbles dimensions vary dynamically based on the chatted text.



We can achieve this dynamic size of cell by calculating size of cell based on displaying text font, size and length.This is very tedious. We can achieve this simply using autolayouts and UITableView automatic dimension setting for row height.

First, Take your label and give below constraints. Constraint constants can be of your choice.

  1. top
  2. leading
  3. trailing &
  4. bottom




After that make label as multiline by giving number of Lines as 0 and Line Break as 'Word Wrap'.

Lines - 0
Line Break - Word Wrap






In the code, give the below settings to UITableView.


  
        self.tableViewRank.estimatedRowHeight = 500
      self.tableViewRank.rowHeight = UITableViewAutomaticDimension


That’s it. Now, Table view’s cells will be of dynamic height based on the label’s content.





Hope this post is useful. Feel free to comment incase of any queries.

Thursday, June 9, 2016

UITableView dequeueReusableCellWithIdentifier

In the UITableView data source delegate method 'cellForRowAtIndexPath', We are supposed to return a UITableViewCell instance. We should be careful here with respect to the performance of the UITableView.

If our table view is going to be static, We can directly allocated and initialize UITableViewCell and return that cell in the delegate method. As the table view is not scrollable (having less data), all the cell intializations will happen only one time.


                         




Approach #1





  - (UITableViewCell *)tableView:(UITableView *)tableView 
                cellForRowAtIndexPath:(NSIndexPath *)indexPath 
                                                                                  
 {  
    
      static NSString *CellIdentifier = @"Categories";
    
      UITableViewCell *cell = [[UITableViewCell alloc] 
                                                 initWithStyle:UITableViewCellStyleDefault 
                                                                 reuseIdentifier:@"Categories"];

      [cell setBackgroundColor:[UIColor clearColor]];        
        
      cell.textLabel.text = str;
      [cell.textLabel setTextColor:[UIColor whiteColor]];
    
    
      return cell;

 }



To know more about static variables, You can have a look at,


What If there are hundreds or thousands of cells needs to be created when there is huge data we need to display. Every time when user scrolls each and everytime gets intialized every time. This is definitely a hit on tableview's performance and also based on user scrolling lodas of memory may get allocated for the cells. If our cell is having so many custom subviews in it, Then  the situation will get more worse.

With our Approach #1, If we have some 200 records, We are initializing all the cells though the cells are having same format. Definitely, this approach doesn't work for huge data.

To avoid this perform hit and memory usage, We can use tableview's dequeueReusableCellWithIdentifier, Which reuses already created cell.

Let's change our Approach #1 and use the dequeueReusableIdentifier and see what happens.


Approach #2 (dequeueReusableCellWithIdentifier)





  - (UITableViewCell *)tableView:(UITableView *)tableView 
                                      cellForRowAtIndexPath:(NSIndexPath *)indexPath
                                                                                        
  {  
    
      static NSString *CellIdentifier = @"Categories";
    
      UITableViewCell *cell = [tableView 
                                            dequeueReusableCellWithIdentifier:CellIdentifier];
    
      NSString *str = [NSString stringWithFormat:@"cell - %ld",(long)indexPath.row];
    
      if(cell == nil){        
        
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                                                       reuseIdentifier:@"Categories"];

          [cell setBackgroundColor:[UIColor clearColor]];
        
      }    
    
      cell.textLabel.text = str;
      [cell.textLabel setTextColor:[UIColor whiteColor]];    
    
      return cell;


  }



This Approach #2 checks first whether there is any reusable cell is available and uses that cell for creating any new cell. If there is no cell available for reuse, We can go for a new cell initialization.

Place a breakpoint in the cell == nil condition, to check how many times the cell initializations is happening.

Here, You may get a question like, With this approach, 

1. How many cells will get initialized?
2. How this approach mitigates/avoids performance hit and memory usage?


                         



Let me give answers to those questions one by one.


1. How many cells will get initialized?


Let's give a height of 200px to our tableview and cell height as 40px.




  [self.myTableView setFrame:CGRectMake(25, 100, 300, 200)];

  - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:
           (NSIndexPath *)indexPath{
    
      return 40;


  }



So we will be having (200%40 = ) 5 visible cells. 5 cells will be initialized first.


cell - 0
cell - 1
cell - 2
cell - 3
cell - 4


When user starts scrolling, The 6th cell (cell - 5) will get initialized. That's it. After that, There won't be any cell initializations. The table starts reusing these already initialized cells. Though you are having 1000 cells after that, There won't be any cell initializations.

So, Only 6 cells will go inside cell == nil condition.




    if(cell == nil){        
        
        cell = [[UITableViewCell alloc] initWithStyle:
                          UITableViewCellStyleDefault reuseIdentifier:@"Categories"];
                                                                                
        [cell setBackgroundColor:[UIColor clearColor]];
        

    }    



Technically, though we have 1000 cells only visible cells +1 will only get initialized.

In our case, only 6 (5 visible +1) cells will get initialized.


2. How this approach mitigates/avoids performance hit and memory usage?


With this approach, Instead of creating 1000 cells, We are reusing the cells created. That's how the performance of the tableview will also get improved a lot as we are not creating new cells every time the user scrolls. The table view becomes very smooth while scrolling and gives a very good user experience.

Hope this post is useful. Feel free to comment incase of any queries.





Tuesday, February 9, 2016

Objective C UITableViewCell height based on content

Usually we set a height for table view cell in the heightForRowAtIndexPath delegate method. If our content text is more on the textLabel, we go for the middle or tail truncation of the text. When user clicks on the cell we open a view and display the full content generally.

What If you got a requirement like, we have to show all the content without any truncations in the cell. In this case the challenge is, cell height should be dynamic based on the content length. In this post let's see how we can achieve this functionality.


                         



From iOS 7.0 we have boundingRectWithSize string method, which gives us the frame required for a string based on the below factors.


  • Maximum width of the label in which we are going to display our text.
  • The label font type and size that we are using.



  
  NSString *message = @"-----LONG CONTENT HERE-----";

  CGSize maximumLabelSize = CGSizeMake(IS_IPA?300-80:180-80, CGFLOAT_MAX);
    
  CGRect textRect = [message boundingRectWithSize:maximumLabelSize

                                             options:NSStringDrawingUsesLineFragmentOrigin| 
                                                         NSStringDrawingUsesFontLeading

                                             attributes:@{NSFontAttributeName:
                                             [UIFont fontWithName:@"Verdana" size:14]} context:nil];                                                                                     


    
Use the above logic in your heightForRowAtIndexPath delegate method and take height from the frame that is given by the boundingRectWithSize method.


Hope this post is useful. Fell free to comment in case of any queries.