zoukankan      html  css  js  c++  java
  • iOS实现页面既显示WebView,WebView下显示TableView,动态计算WebView内容高度

    实现效果如下:

    忽略底部的评论视图,太丑了,待完善......

    实现思路:

    1>页面布局采用TableView实现,顶部"关注"模块的View是TableView的tableHeaderView;

    2>采用两个cell,webViewCell和CommentCell,indexPath.row == 0使用webViewCell,其余使用CommentCell;

    3>在webViewCell的webView的代理方法中webViewDidFinishLoad计算webView内容的实际高度,block回调控制器刷新indexPath.row == 0的cell即可.

    4>tableView代理返回cell直接返回cell里计算的cell.

    代码实现如下:

    WebViewCell:

    #import <UIKit/UIKit.h>
    typedef void (^ReloadBlock)();
    @interface WebviewCell : UITableViewCell
    
    @property(nonatomic, copy) NSString *htmlString;
    @property(nonatomic, copy) ReloadBlock reloadBlock;
    
    +(CGFloat)cellHeight;
    
    @end
    #import "WebviewCell.h"
    @interface WebviewCell()<UIWebViewDelegate>
    
    @property(nonatomic,strong)UIWebView *webview;
    
    @end
    static CGFloat staticheight = 0;
    
    @implementation WebviewCell
    
    +(CGFloat)cellHeight
    {
        return staticheight;
    }
    -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        if (self = [super initWithStyle: style reuseIdentifier:reuseIdentifier]) {
            
    //        self.webview.scrollView.backgroundColor =[UIColor redColor];
            [self.contentView addSubview:self.webview];
        }
        return self;
        
    }
    -(void)setHtmlString:(NSString *)htmlString
    {
        _htmlString = htmlString;
        
        self.webview.delegate = self;
        // 否则导致网页下方留出了多余的空白
        // 手动改变图片适配问题,拼接html代码后,再加载html代码
        NSString *myStr = [NSString stringWithFormat:@"<head><style>img{max-    %f !important;}</style></head>", [UIScreen mainScreen].bounds.size.width - 20];
        NSString *str = [NSString stringWithFormat:@"%@%@",myStr, htmlString];
        [self.webview loadHTMLString:str baseURL:nil];
    }
    
    -(void)webViewDidFinishLoad:(UIWebView *)webView
    {
        CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]+20 ;
        self.webview.frame = CGRectMake(0, 0, K_SCREEN_WIDTH, height);
        self.webview.hidden = NO;
        if (staticheight != height+1) {
            staticheight = height+1;
            if (staticheight > 0) {
                if (_reloadBlock) {
                    _reloadBlock();
                }
            }
        }
    }
    
    -(UIWebView *)webview {
        
        if (!_webview) {
            _webview =[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, K_SCREEN_WIDTH, 0)];
            _webview.userInteractionEnabled = NO;
            _webview.hidden = YES;
        }
        return _webview;
    }
    @end

    评论cell和tableHeaderView这里就不贴代码了,很简单的....

    控制器代码: 这里都贴上了...自己找重点哟!!!

    #import "NewDetailViewController.h"
    #import "NewDetailHeaderView.h"
    #import "CommentBottomView.h"
    #import "HTTPTool.h"
    #import "HDNewsDetailModel.h"
    #import "News.h"
    #import "UIColor+HexColor.h"
    #import "NewDetailCommentModel.h"
    #import "WebviewCell.h"
    #import "DetailCommentCell.h"
    
    @interface NewDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate>
    
    @property (nonatomic, strong) UIWebView *webView;
    @property (nonatomic, strong) NewDetailHeaderView *headerView;
    @property (nonatomic, strong) CommentBottomView *bottomView;
    @property (nonatomic, assign) CGFloat keyBoardHeight;
    @property (nonatomic, assign) CGFloat currentTextViewHeight;
    @property (nonatomic,strong) NSMutableArray *array;
    @property (nonatomic, strong) NSArray *commentArray; // 评论model数组
    @property (nonatomic, strong) UITableView *commnetTableView;
    @property (nonatomic, strong) HDNewsDetailModel *detailModel;
    
    @end
    
    @implementation NewDetailViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.navigationItem.title = @"新闻详情页";
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName : [UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:@"#4bb6ac"];
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.navigationController.navigationBar.translucent = NO;
        self.currentTextViewHeight = 44;
        [self addNotification];
        [self setupHeaderView];
        [self setupBottomView];
        [self setupUI];
        [self addNavShareItem];
        [self requestData];
        [self requestCommentData];
    }
    
    - (void)addNavShareItem {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"1x_fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction:)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    }
    
    #pragma mark - 键盘通知
    - (void)addNotification {
        
        // 监听键盘的弹出
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeHeight:) name:@"changeHeight" object:nil];
        
    }
    
    - (void)keyboardWillShow:(NSNotification *) notification {
        
        float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGFloat height = [[[notification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
        self.keyBoardHeight = height;
        // 没有弹出键盘 使用这种动画比较顺畅一点
        [UIView animateWithDuration:animationDuration animations:^{
            CGRect bottomBarFrame = self.bottomView.frame;
            bottomBarFrame.origin.y = [UIScreen mainScreen].bounds.size.height - height - self.currentTextViewHeight - 64;
            //    CGRect rc = [self.view convertRect: self.bottomView.frame toView:self.view];
            [self.bottomView setFrame:bottomBarFrame];
            // 这里注意: 需要把底部view移动到最前面显示
            [self.view bringSubviewToFront:self.bottomView];
        }];
    }
    
    - (void)keyboardWillHide:(NSNotification *) notification {
        float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGFloat height = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        self.keyBoardHeight = height;
        [UIView animateWithDuration:animationDuration animations:^{
            CGRect bottomBarFrame = self.bottomView.frame;
            bottomBarFrame.origin.y = self.view.bounds.size.height - self.currentTextViewHeight;
            [self.bottomView setFrame:bottomBarFrame];
        }];
    }
    
    - (void)changeHeight: (NSNotification *)notifi {
        CGFloat height = [notifi.userInfo[@"height"] floatValue];
        if (height > 44) {
            
            self.currentTextViewHeight = height;
        }
        NSLog(@"height --- %f",height);
        [UIView animateWithDuration:0.2 animations:^{
            CGRect bottomBarFrame = self.bottomView.frame;
            bottomBarFrame.origin.y = self.view.bounds.size.height - height - self.keyBoardHeight;
            bottomBarFrame.size.height = height + 30;
            [self.bottomView setFrame:bottomBarFrame];
        }];
    }
    
    #pragma mark - 设置界面
    
    - (void)setupUI {
        [self.view addSubview:self.commnetTableView];
        self.commnetTableView.frame = CGRectMake(0, 0, K_SCREEN_WIDTH, K_SCREEN_HEIGHT - 44 - 64);
    }
    
    - (void)setupHeaderView {
        
        self.headerView = [[NewDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 70)];
        self.headerView.focusButtonBlock = ^(BOOL flag) {
            NSLog(@"flag -- %d",flag);
        };
        [self.commnetTableView setTableHeaderView:self.headerView];
    }
    
    - (void)setupBottomView {
        self.bottomView = [[CommentBottomView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44 - 64, [UIScreen mainScreen].bounds.size.width, 44)];
        [self.view addSubview:self.bottomView];
    }
    
    #pragma mark - 数据请求
    
    - (void)requestData {
        NSString *url = [NSString stringWithFormat:@"http://huidu.zhonghuilv.net/Index/newslist?newsid=%@",@(self.model.id)];
       [HTTPTool postWithURL:url headers:nil params:nil success:^(id json) {
           NSLog(@"json = %@",json);
           self.detailModel = [[HDNewsDetailModel alloc]init];
           [self.detailModel setValuesForKeysWithDictionary:json];
    //       self.headerView.model = self.detailModel;
           [self.headerView configureHeaderAvaterWithImage:json[@"thumb"] title:json[@"title"]];
       } failure:^(NSError *error) {
           [CombancHUD showInfoWithStatus:@"加载失败"];
       }];
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        
        return self.commentArray.count + 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        
        if (indexPath.row == 0) {
            WebviewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WebviewCell" forIndexPath:indexPath];
            cell.htmlString = self.detailModel.content;
            __weak NewDetailViewController *weakSelf = self;
            cell.reloadBlock =^()
            {   // 刷新webViewCell
                [weakSelf.commnetTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            return cell;
        }
        DetailCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell" forIndexPath:indexPath];
        cell.model = self.commentArray[indexPath.row - 1];
        return cell;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        
        if (indexPath.row == 0) {
            NSLog(@"cellHeight---%f",[WebviewCell cellHeight]);
            return [WebviewCell cellHeight];
        } else {
            return 78;
        }
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
        
        return 0.001f;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        
        return 0.001f;
    }
    
    - (void)requestCommentData {
        // index/Articlepl
        NSString *url = [NSString stringWithFormat:@"http://huidu.zhonghuilv.net/index/Articlepl?newsid=%@",@(self.model.id)];
        [HTTPTool postWithURL:url headers:nil params:nil success:^(id json) {
            NSLog(@"json = %@",json);
            self.commentArray = [NewDetailCommentModel mj_objectArrayWithKeyValuesArray:json];
            [self.commnetTableView reloadData];
        } failure:^(NSError *error) {
            [CombancHUD showInfoWithStatus:@"加载失败"];
        }];
    }
    
    #pragma mark - Private Method
    
    - (void)shareAction: (UIBarButtonItem *)item {
        NSLog(@"分享");
    }
    
    - (UITableView *)commnetTableView {
        if (!_commnetTableView) {
            _commnetTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
            _commnetTableView.delegate = self;
            _commnetTableView.dataSource = self;
            [_commnetTableView registerNib:[UINib nibWithNibName:@"DetailCommentCell" bundle:nil] forCellReuseIdentifier:@"CommentCell"];
            [_commnetTableView registerClass:[WebviewCell class] forCellReuseIdentifier:@"WebviewCell"];
            _commnetTableView.tableHeaderView = [UIView new];
            _commnetTableView.tableFooterView = [UIView new];
        }
        return _commnetTableView;
    }
    
    @end
  • 相关阅读:
    Project Euler 97 :Large non-Mersenne prime 非梅森大素数
    Project Euler 96:Su Doku 数独
    Project Euler 95:Amicable chains 亲和数链
    Project Euler 94:Almost equilateral triangles 几乎等边的三角形
    Project Euler 93:Arithmetic expressions 算术表达式
    Project Euler 92:Square digit chains 平方数字链
    Project Euler 91:Right triangles with integer coordinates 格点直角三角形
    Project Euler 90:Cube digit pairs 立方体数字对
    Project Euler 89:Roman numerals 罗马数字
    Project Euler 88:Product-sum numbers 积和数
  • 原文地址:https://www.cnblogs.com/pengsi/p/7299796.html
Copyright © 2011-2022 走看看