在UITableView中选择单元格似乎在iPad和iPhone上工作不同。
在iPhone上,我看到以下行为:
但是在iPad上,我观察到了以下行为:
使UITableView在iPad上像在iPhone上一样工作的最干净的方法是什么?
这是重现该问题的最小应用程序。它基于Xcode 5的“空应用程序”模板。它同时在iOS 7和6.1上发生。
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UITableViewController
@end
ViewController.m
#import "ViewController.h"
@implementation ViewController
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 42;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [@(indexPath.row) stringValue];
return cell;
}
@end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
ViewController *viewController = [[ViewController alloc] init];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
return YES;
}
@end
最佳答案
这是因为UITableView
在touchesBegan
期间取消选择了选定的行。这似乎只发生在iPad上,而不发生在iPhone上。不知道为什么会有区别。
为了使iPad版本的行为类似于iPhone版本,我最终对UITableView进行了子类化以覆盖此行为。我希望对这个问题有更好的答案,但这是我的解决方案:
@interface CustomTableView : UITableView
@property (nonatomic) BOOL inTouchSequence;
@end
@implementation CustomTableView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.inTouchSequence = YES;
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.inTouchSequence = NO;
[super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.inTouchSequence = NO;
[super touchesCancelled:touches withEvent:event];
}
@end
然后在我的自定义单元格中,添加了对
tableView
的引用,并覆盖了setSelected
方法,以防止touchesBegan
取消选择单元格。@interface CustomTableViewCell : UITableViewCell
@property (weak, nonatomic) CustomTableView* tableView;
@end
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
if (self.tableView.inTouchSequence) {
// Skip deselection while tableview is being touched.
return;
}
[super setSelected:selected animated:animated];
// Custom selection logic
}
关于ios - UITableView失去当前选择,而手指临时触摸另一行,仅在iPad上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21460892/