IOS UITableView实现单选功能
// 实现功能:没有任何操作前默认选中第0行。操作后记录选择最后的行,下次进入会显示上一次选中的行
- ( void ) viewDidAppear: ( BOOL ) animated {[ super viewDidAppear : animated ];// 读取上一次选择的cellNSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ];NSIndexPath * indexpath = [ NSIndexPath indexPathForRow : [ defaults integerForKey : @"selectedRow" ] inSection : 0 ];// 设置默认选中行[ self . tableView selectRowAtIndexPath : indexpath animated : YES scrollPosition : UITableViewScrollPositionNone ];[ self tableView : self . tableView didSelectRowAtIndexPath : indexpath ];[ self . tableView reloadData ];}
- ( UITableViewCell * ) tableView: ( UITableView * ) tableView cellForRowAtIndexPath: ( NSIndexPath * ) indexPath{static NSString * reuseID = @"WMLauageCell" ;WMLauageCell * cell = [ tableView dequeueReusableCellWithIdentifier : reuseID ];if ( cell == nil ){cell = [[ WMLauageCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier : reuseID ];cell . contentView . backgroundColor = [ UIColor lightTextColor ];UIView * backGroundView = [[ UIView alloc ] init ];backGroundView . backgroundColor = [ UIColor lightTextColor ];cell . selectedBackgroundView = backGroundView ;}cell . language . text = self . languageArray [ indexPath . row ];cell . indationIcon . image = SET_IMAGE ( @"check_box_s" );NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ];NSIndexPath * path = [ NSIndexPath indexPathForRow : [ defaults integerForKey : @"selectedRow" ] inSection : 0 ];if ( self . isFirst && path . row == indexPath . row ){self . isFirst = NO ;cell . indationIcon . hidden = NO ;}return cell ;}
- ( void ) tableView: ( UITableView * ) tableView didSelectRowAtIndexPath: ( NSIndexPath * ) indexPath {[[ NSUserDefaults standardUserDefaults ] setInteger : indexPath . row forKey : @"selectedRow" ];[[ NSUserDefaults standardUserDefaults ] synchronize ];NSUInteger newRow = indexPath . row ;NSUInteger oldRow = [ self . lastIndexPath row ];if ( newRow != oldRow ){WMLauageCell * newCell = [ tableView cellForRowAtIndexPath :indexPath ];newCell . indationIcon . hidden = NO ;WMLauageCell * oldCell = [ tableView cellForRowAtIndexPath :self . lastIndexPath ];oldCell . indationIcon . hidden = YES ;self . lastIndexPath = indexPath ;}
}