How to only override a method depending on the runtime system iOS version?

一笑奈何 提交于 2019-11-26 21:16:47

问题


I've implemented automatic dynamic tableview cell heights for iOS 8 by using

self.tableView.rowHeight = UITableViewAutomaticDimension;

For pre-iOS 8, which does not support automatic dynamic cell heights, I overrided the heightForRowAtIndexPath method.

This is a similar to what I did: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

The problem is to how to write code that uses automatic cell height for iOS 8 but overrides heightForRowAtIndexPath for earlier iOS versions. I'd like my custom heightForRowAtIndexPath method only if iOS version is less than 8. Any suggestions on how to do this?


回答1:


One solution would be to override the respondsToSelector: method in your view controller. Have it return NO under iOS 8 when checking for the heightForRowAtIndexPath: method.

- (BOOL)respondsToSelector:(SEL)selector {
    static BOOL useSelector;
    static dispatch_once_t predicate = 0;
    dispatch_once(&predicate, ^{
        useSelector = [[UIDevice currentDevice].systemVersion floatValue] < 8.0 ? YES : NO;
    });

    if (selector == @selector(tableView:heightForRowAtIndexPath:)) {
        return useSelector;
    }

    return [super respondsToSelector:selector];
}

This way, when the table view make a call like:

if ([self.delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {
}

your code will return NO under iOS 8 or later and YES under iOS 7 or earlier.




回答2:


I found a simple solution. Declared this macro to recognize if user has iOS 8.0 or later:

#define IS_IOS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

Then, inside heightForRowAtIndexPath I added the following code:

if (IS_IOS_8_OR_LATER) {
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        return self.tableView.rowHeight;
    } else {//Custom code for ios version earlier than 8.0

}

This solved the problem



来源:https://stackoverflow.com/questions/26022113/how-to-only-override-a-method-depending-on-the-runtime-system-ios-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!