Search code examples
iosuitableviewuiwebviewuiwebviewdelegate

Inside UITableViewCell, I am getting delegate callback of old UIWebView?


I have custom cell inside which there is UIWebView and based on its content height, I am setting height for that row. This is done after I get following delegate call:

- (void)webViewDidFinishLoad:(UIWebView *)webView

Here is what I am doing:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    /* Webview content height change works only if 0.1 sec delay given */

    [GlobalClass delay:^{

        webViewHeight = webView.scrollView.contentSize.height;
        // If I log this, it prints old height
        [tblOptions reloadData];

    } seconds:0.1]; 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) 
    {
        case 0: {
            return webViewHeight;
        }
        case 1: {
            return UITableViewAutomaticDimension;
        }
        case 2: {
            return 60;
        }
        default:
            return 0;
    }
}

Now, if first cell is loaded, I am getting perfect height (55) but when second cell loads which have large content (800) but it is giving (55). If I go back then it should be (55), but at that time, it gives (800).

In short, it gives me previous height instead of the current webview height.

Here is my delay function:

+ (void)delay:(void(^)(void))callback seconds:(double)delayInSeconds
{    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(callback){
            callback();
        }
    });
}

Solution

  • Well, I think you need to provide a little more context to your issue. What I am understanding is: there are many cells (I assumed based on what you said "when second cell loads") in the UITableView and each has dynamic height depending on its UIWebView content. If it is then here are some issues of I found your code:

    • You are using a single global variable webViewHeight to return to the delegate heightForRowAtIndexPath (it means all of your cells will have this height) which leads to the incorrect value you are getting. To solve this issue, you can cache those values in a dictionary instead.
    • I saw you reload your UITableView every time a UIWebView is loaded, so if you start loading your UIWebView somewhere in cellForRowAtIndexPath it might cause infinite loop.