detect changes to UIWebView's scroll view's contentSize

后端 未结 2 1328
南旧
南旧 2020-12-25 15:38

I\'m trying to set a UIView at the bottom of the content of a UIScrollView, do to so I set the view\'s position to the scrollview\'s contentsize height. But my scrollview is

2条回答
  •  长情又很酷
    2020-12-25 16:02

    Your approach is half correct. You can surely override an existing method through a category, what you cannot do, though is accessing an ivar of the class.

    In this case, what you need is method swizzling: you override setContentSize while at the same time keeping a reference to the original implementation of the method, so you can call it to set _contentSize value.

    Here is the code that you could use, with comments:

    @implementation UIScrollView (Height)
    
    // -- this method is a generic swizzling workhorse
    // -- it will swap one method impl with another and keep the old one
    // under your own impl name
    + (void)swizzleMethod:(SEL)originalSel andMethod:(SEL)swizzledSel {
    
      Method original = class_getInstanceMethod(self, originalSel);
      Method swizzled = class_getInstanceMethod(self, swizzledSel);
      if (original && swizzled)
         method_exchangeImplementations(original, swizzled);
      else
        NSLog(@"Swizzling Fault: methods not found.");
    
    }    
    
    //-- this is called on the very moment when the categoty is loaded
    //-- and it will ensure the swizzling is done; as you see, I am swapping
    //-- setContentSize and setContentSizeSwizzled;
    + (void)load {
      [self swizzleMethod:@selector(setContentSize:) andMethod:@selector(setContentSizeSwizzled:)];
    }
    
    //-- this is my setContentSizeSwizzled implementation;
    //-- I can still call the original implementation of the method
    //-- which will be avaiable (*after swizzling*) as setContentSizeSwizzled
    //-- this is a bit counterintuitive, but correct!
    - (void)setContentSizeSwizzled:(CGSize)contentSize
    {
      [self setContentSizeSwizzled:contentSize];
      [[NSNotificationCenter defaultCenter] postNotification:[NSNotification    notificationWithName:@"scrollViewContentSizeChanged" object:nil]];
    }
    
    @end
    

    Hope it helps.

提交回复
热议问题