你的方法对了一半。您当然可以通过类别覆盖现有方法,但您不能做的是访问该类的 ivar。
在这种情况下,您需要的是方法调配:您在覆盖setContentSize
的同时保留对该方法的原始实现的引用,因此您可以调用它来设置_contentSize
值。
这是您可以使用的代码,带有注释:
@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
希望能帮助到你。