LoginSignup
5
4

More than 5 years have passed since last update.

UIWebViewのScrollViewにフッターを作成する

Last updated at Posted at 2014-12-10

UIWebViewで表示されているコンテンツの下にフッターとしてUIViewを追加する実装をしなければいけなったためメモ。
調べてもスクロールしない固定フッターの情報ぐらいしかなかなかなかったので。

参考:https://github.com/coryalder/DMAFWebViewController

フッターの作成

@property (strong, nonatomic) UIView *footerView;

- (void)createFooter {
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
}

ScrollViewのコンテンツサイズを監視

[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

KVOはdeallocで開放してください

- (void)dealloc {
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
}

コンテンツサイズの変更にあわせてフッターを追加

#import <objc/runtime.h>

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentSize"] && self.footerView) {
        NSNumber *incumbentheight = objc_getAssociatedObject(object, "associated_height");
        NSValue *newValue = [change objectForKey:NSKeyValueChangeNewKey];
        CGSize newSize;
        [newValue getValue:&newSize];

        if (!incumbentheight || [incumbentheight floatValue] != newSize.height) {
            CGFloat newHeight = newSize.height + self.footerView.frame.size.height;

            if (!self.footerView.superview) {
                [self.webView.scrollView addSubview:self.footerView];
            } else if ([self.footerView superview] != self.webView.scrollView) {
                [self.footerView removeFromSuperview];
                [self.webView.scrollView addSubview:self.footerView];
            }

            self.footerView.frame = (CGRect){0,newSize.height, .size = self.footerView.frame.size};

            objc_setAssociatedObject(object, "associated_height", @(newHeight), OBJC_ASSOCIATION_COPY);

            self.webView.scrollView.contentSize = (CGSize){newSize.width, newSize.height+self.footerView.frame.size.height};

        } else {
            objc_setAssociatedObject(object, "associated_height", @(newSize.height), OBJC_ASSOCIATION_COPY);
        }

    }
}

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4