问题
A UITableView should bounce (even when empty) when user scrolls as long as the bounces
and alwaysBounceVertical
properties are set to YES. When I initialize a UITableViewController, everything works as expected. When I initialized a UIViewController loaded from a nib with a simple view hierarchy: a top level UIView with a single UITableView child, then the table view doesn't bounce anymore. Here is the code I used:
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, UITableViewDataSource>
@end
@implementation AppDelegate
@synthesize window = _window;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIViewController *rootViewController = nil;
UITableView *tableView;
BOOL loadFromNib = NO;
if (loadFromNib)
{
rootViewController = [[UIViewController alloc] initWithNibName:@"ViewController" bundle:nil];
tableView = [rootViewController.view.subviews objectAtIndex:0];
}
else
{
rootViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
tableView = (UITableView *)rootViewController.view;
}
tableView.dataSource = self;
NSLog(@"%@ bounces: %@", tableView.class, tableView.bounces ? @"YES" : @"NO");
NSLog(@"%@ alwaysBounceVertical: %@", tableView.class, tableView.alwaysBounceVertical ? @"YES" : @"NO");
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
@end
When I run this code with the loadFromNib
variable set to YES or NO, it always logs this:
UITableView bounces: YES
UITableView alwaysBounceVertical: YES
But when I load it from the nib (i.e. loadFromNib
is set to YES), the table view doesn’t bounce when I try to scroll. Why doesn’t it bounce?
回答1:
I cannot precisely explain why, but the behaviour with empty table views seems pretty erratic. Anyway, setting tableView.bounces = YES
manually (e.g. in the -viewDidLoad
method of the view controller the table view belongs to) fixes such issues and ensures that your table view always bounces, even when empty.
来源:https://stackoverflow.com/questions/12316055/empty-uitableview-not-bouncing-when-loaded-from-a-nib