UIWebView增加头部尾部

一:webViw的头部实现比较简单,代码如下:

   //@property(nonatomic)UIEdgeInsetscontentInset; 这个属性能够在UIScrollView的4周增加额外的滚动区域 

   //默认的是(0,0,0,0),这样就能空出一个240的区域

        self.contWeb.scrollView.contentInset  = UIEdgeInsetsMake(240, 0, 0, 0);

        UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, -240, KScreenWidth, 240)];

        [head setBackgroundColor:[UIColor redColor]];        

        [self.contWeb.scrollView addSubview:head];

        [self addObserverForWebViewContentSize];

二:webView的尾部由于不知道加载的HTML的所占区域,所以在尾部不能使用跟头部一样的方法直接设置,需要获取HTML所占的高度

    //监听contentSize事件

    - (void)addObserverForWebViewContentSize{

        [self.contWeb.scrollView addObserver:self forKeyPath:@"contentSize" options:0 context:nil];

    }

    //移除监听事件

    - (void)removeObserverForWebViewContentSize{

        [self.contWeb.scrollView removeObserver:self forKeyPath:@"contentSize"];

    }

    //以下是监听结果回调事件:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void       *)context

    {  

        //在监听回调里添加webView尾部

        [self layoutCell];

      }

    //设置footerView的合理位置

    - (void)layoutCell{

        //取消监听,因为这里会调整contentSize,避免循环,无限递归

        [self removeObserverForWebViewContentSize];

        CGSize contentSize = self.contWeb.scrollView.contentSize;

        UIView *foot = [[UIView alloc]init];

        [foot setBackgroundColor:[UIColor blueColor]];

        foot.frame = CGRectMake(0, contentSize.height, KScreenWidth, 240);

        [self.contWeb.scrollView addSubview:foot];

        self.contWeb.scrollView.contentSize = CGSizeMake(contentSize.width, contentSize.height + 240);

        //重新监听

        [self addObserverForWebViewContentSize];

      }

      直接调取添加监听事件那个方法就能使用

原文地址:https://www.cnblogs.com/var-king/p/6004082.html