如何更新 TableView 静态单元格中的数据?

Posted

技术标签:

【中文标题】如何更新 TableView 静态单元格中的数据?【英文标题】:How Can I update the data in TableView Static Cells? 【发布时间】:2017-07-14 04:05:39 【问题描述】:

我想更新计数的值,但我不能这样做..!我试过了,但是当我构建代码时它会更新......!

这是一个表格视图的截图:

这是代码,

#import "LeftMenuViewController.h"
#import "RKDropdownAlert.h"
#import "HexColors.h"
#import "AppConstanst.h"
#import "GlobalVariables.h"
#import "MyWebservices.h"
#import <SDWebImage/UIImageView+WebCache.h>
@import Firebase;
@interface LeftMenuViewController ()
    NSUserDefaults *userDefaults;
    GlobalVariables *globalVariables;
    NSArray *numbers;

@end

@implementation LeftMenuViewController

- (id)initWithCoder:(NSCoder *)aDecoder

    self.slideOutAnimationEnabled = YES;

    return [super initWithCoder:aDecoder];


- (void)viewDidLoad 
    [super viewDidLoad];

    NSLog(@"Naaa-LeftMENU");


    self.tableView.tableFooterView=[[UIView alloc] initWithFrame:CGRectZero];



-(void)viewWillAppear:(BOOL)animated

    userDefaults=[NSUserDefaults standardUserDefaults];
    globalVariables=[GlobalVariables sharedInstance];
     NSLog(@"Role : %@",[userDefaults objectForKey:@"role"]);
    _user_role.text=[[userDefaults objectForKey:@"role"] uppercaseString];

    _user_nameLabel.text=[userDefaults objectForKey:@"profile_name"];
    _url_label.text=[userDefaults objectForKey:@"baseURL"];

    [_user_profileImage sd_setImageWithURL:[NSURL URLWithString:[userDefaults objectForKey:@"profile_pic"]]
                          placeholderImage:[UIImage imageNamed:@"default_pic.png"]];
    _user_profileImage.layer.borderColor=[[UIColor hx_colorWithHexRGBAString:@"#0288D1"] CGColor];

    _user_profileImage.layer.cornerRadius = _user_profileImage.frame.size.height /2;
    _user_profileImage.layer.masksToBounds = YES;
    _user_profileImage.layer.borderWidth = 0;



    NSInteger open =  [globalVariables.OpenCount integerValue];
    NSInteger closed = [globalVariables.ClosedCount integerValue];
    NSInteger trash = [globalVariables.DeletedCount integerValue];
    NSInteger unasigned = [globalVariables.UnassignedCount integerValue];
    NSInteger my_tickets = [globalVariables.MyticketsCount integerValue];

    if(open>999)
        _inbox_countLabel.text=@"999+";
    else
        _inbox_countLabel.text=@(open).stringValue;
    if(closed>999)
        _closed_countLabel.text=@"999+";
    else
        _closed_countLabel.text=@(closed).stringValue;
    if(trash>999)
        _trash_countLabel.text=@"999+";
    else
        _trash_countLabel.text=@(trash).stringValue;
    if(unasigned>999)
        _unassigned_countLabel.text=@"999+";
    else
        _unassigned_countLabel.text=@(unasigned).stringValue;
    if(my_tickets>999)
        _myTickets_countLabel.text=@"999+";
    else
        _myTickets_countLabel.text=@(my_tickets).stringValue;

    [self.tableView reloadData];



- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
                                                             bundle: nil];

    // UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    UIViewController *vc ;

    switch (indexPath.row)
    
        case 1:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"CreateTicket"];
            break;

        case 2:
            [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
            break;
        case 3:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"InboxID"];
            break;
        case 4:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"MyTicketsID"];
            break;
        case 5:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"UnassignedTicketsID"];
            break;
        case 6:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"ClosedTicketsID"];
            break;

        case 7:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"TrashTicketsID"];
            break;

        case 8:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"ClientListID"];
            break;

        case 10:
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"AboutVCID"];
            break;


        case 11:

            [self wipeDataInLogout];
            //[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
            //[[SlideNavigationController sharedInstance] popToRootViewControllerAnimated:NO];

            [RKDropdownAlert title:@"Faveo Helpdesk" message:@"You've logged out, successfully." backgroundColor:[UIColor hx_colorWithHexRGBAString:SUCCESS_COLOR] textColor:[UIColor whiteColor]];
            vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"Login"];
            // (vc.view.window!.rootViewController?).dismissViewControllerAnimated(false, completion: nil);
            break;


        default:
            break;
    

    [[SlideNavigationController sharedInstance] popToRootAndSwitchToViewController:vc
                                                             withSlideOutAnimation:self.slideOutAnimationEnabled
                                                                     andCompletion:nil];


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath


    if (indexPath.row == 9) 
        return 0;
     else 
        return [super tableView:tableView heightForRowAtIndexPath:indexPath];
    



-(void)wipeDataInLogout

    [self sendDeviceToken];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"faveoData.plist"];
    NSError *error;
    if(![[NSFileManager defaultManager] removeItemAtPath:plistPath error:&error])
    
        NSLog(@"Error while removing the plist %@", error.localizedDescription);
        //TODO: Handle/Log error
    

    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) 
        [cookieStorage deleteCookie:each];
    



-(void)sendDeviceToken

   // NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSString *url=[NSString stringWithFormat:@"%@fcmtoken?user_id=%@&fcm_token=%s&os=%@",[userDefaults objectForKey:@"companyURL"],[userDefaults objectForKey:@"user_id"],"0",@"ios"];
    MyWebservices *webservices=[MyWebservices sharedInstance];
    [webservices httpResponsePOST:url parameter:@"" callbackHandler:^(NSError *error,id json,NSString* msg)
        if (error || [msg containsString:@"Error"]) 
            if (msg) 

                // [utils showAlertWithMessage:[NSString stringWithFormat:@"Error-%@",msg] sendViewController:self];
                NSLog(@"Thread-postAPNS-toserver-error == %@",error.localizedDescription);
            else if(error)  
                //                [utils showAlertWithMessage:[NSString stringWithFormat:@"Error-%@",error.localizedDescription] sendViewController:self];
                NSLog(@"Thread-postAPNS-toserver-error == %@",error.localizedDescription);
            
            return ;
        
        if (json) 

            NSLog(@"Thread-sendAPNS-token-json-%@",json);
        

    ];


- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    // rows in section 0 should not be selectable
    // if ( indexPath.section == 0 ) return nil;

    // first 3 rows in any section should not be selectable
    if ( (indexPath.row ==0) || (indexPath.row==2) ) return nil;

    // By default, allow row to be selected
    return indexPath;



@end

【问题讨论】:

写在CellForRowAtIndexPath而不是ViewWillAppear 您无法更新静态单元格,因此标题为 Static。如果您想要动态数据,为什么不使用动态单元格? 好主意....!让我检查一下..! 【参考方案1】:

做一件事,在viewDidLoad方法中添加方法

[self update];

然后,在此方法中添加该代码。

-(void)update


    userDefaults=[NSUserDefaults standardUserDefaults];
    globalVariables=[GlobalVariables sharedInstance];
    NSLog(@"Role : %@",[userDefaults objectForKey:@"role"]);
    _user_role.text=[[userDefaults objectForKey:@"role"] uppercaseString];

    _user_nameLabel.text=[userDefaults objectForKey:@"profile_name"];
    _url_label.text=[userDefaults objectForKey:@"baseURL"];

    [_user_profileImage sd_setImageWithURL:[NSURL URLWithString:[userDefaults objectForKey:@"profile_pic"]]
                          placeholderImage:[UIImage imageNamed:@"default_pic.png"]];
    _user_profileImage.layer.borderColor=[[UIColor hx_colorWithHexRGBAString:@"#0288D1"] CGColor];

    _user_profileImage.layer.cornerRadius = _user_profileImage.frame.size.height /2;
    _user_profileImage.layer.masksToBounds = YES;
    _user_profileImage.layer.borderWidth = 0;


    _view1.alpha=0.5;
    _view1.layer.cornerRadius = 20;
    _view1.backgroundColor = [UIColor purpleColor];

    _view2.alpha=0.5;
    _view2.layer.cornerRadius = 20;
    _view2.backgroundColor = [UIColor purpleColor];


    _view3.alpha=0.5;
    _view3.layer.cornerRadius = 20;
    _view3.backgroundColor = [UIColor purpleColor];


    _view4.alpha=0.5;
    _view4.layer.cornerRadius = 20;
    _view4.backgroundColor = [UIColor purpleColor];

    _view5.alpha=0.5;
    _view5.layer.cornerRadius = 20;
    _view5.backgroundColor = [UIColor purpleColor];


    NSInteger open =  [globalVariables.OpenCount integerValue];
    NSInteger closed = [globalVariables.ClosedCount integerValue];
    NSInteger trash = [globalVariables.DeletedCount integerValue];
    NSInteger unasigned = [globalVariables.UnassignedCount integerValue];
    NSInteger my_tickets = [globalVariables.MyticketsCount integerValue];

    if(open>99)
        _c1.text=@"99+";
    else
        _c1.text=@(open).stringValue;
    if(closed>99)
        _c4.text=@"99+";
    else
        _c4.text=@(closed).stringValue;
    if(trash>99)
        _c5.text=@"99+";
    else
        _c5.text=@(trash).stringValue;
    if(unasigned>99)
        _c3.text=@"99+";
    else
        _c3.text=@(unasigned).stringValue;
    if(my_tickets>99)
        _c2.text=@"99+";
    else
        _c2.text=@(my_tickets).stringValue;

    [self.tableView reloadData];


并添加此代码,

-(void)viewWillAppear:(BOOL)animated

 [self.tableView reloadData];
    //[self.tableView reloadData];


并在 viewDidLoad 方法中调用 getDependencies 方法。 检查一次,让我知道..!

【讨论】:

我检查过但....有时它会加载,有时或不...!我从 viewWillAppear 调用 getDependencies 方法,所以我可以在数据出现之前加载数据,我的意思是调用 getDependencies 方法并且值将更新..!对吗? 在viewDidLoad中调用getDependencies,这里也调用update方法..!不要在 viewWillAppear 方法中调用 getDependencies...!并使用 [self.tableView reloadData];方法重新加载表格视图...!它会工作..!【参考方案2】:

您可以为所有需要更新的标签创建IBOutlet。您可以在控制器类中的任何位置更新计数,而不是在更新计数时重新加载 tableview。您可以在单独的方法中移动与更新计数相关的所有代码,并在需要时调用此方法。

 func updateAllLabels() 
    NSInteger open =  [globalVariables.OpenCount integerValue];
    NSInteger closed = [globalVariables.ClosedCount integerValue];
    NSInteger trash = [globalVariables.DeletedCount integerValue];
    NSInteger unasigned = [globalVariables.UnassignedCount integerValue];
    NSInteger my_tickets = [globalVariables.MyticketsCount integerValue];

    if(open>999)
        _inbox_countLabel.text=@"999+";
    else
        _inbox_countLabel.text=@(open).stringValue;
    if(closed>999)
        _closed_countLabel.text=@"999+";
    else
        _closed_countLabel.text=@(closed).stringValue;
    if(trash>999)
        _trash_countLabel.text=@"999+";
    else
        _trash_countLabel.text=@(trash).stringValue;
    if(unasigned>999)
        _unassigned_countLabel.text=@"999+";
    else
        _unassigned_countLabel.text=@(unasigned).stringValue;
    if(my_tickets>999)
        _myTickets_countLabel.text=@"999+";
    else
        _myTickets_countLabel.text=@(my_tickets).stringValue;

并在值更新时调用此updateAllLabels 方法。如果您知道只有一个值会得到更新,则只能更新该标签。

【讨论】:

以上是关于如何更新 TableView 静态单元格中的数据?的主要内容,如果未能解决你的问题,请参考以下文章

点击时更新 tableView 单元格中的 Firebase 数据

将数据从容器视图中的 tableview 中的静态单元格发送到 Swift 中的视图控制器

TableView 交互阻止单元格中的动画

如何通过单击单元格中的按钮来删除 tableView 中的单元格?使用核心数据

如何将当前单元格中的数据与 TableView Swift 4 中的前一个单元格进行比较?

如何使tableView中单元格中的图像一致显示?