简体   繁体   English

为什么在目标 c 中重新加载表视图时选择的值会取消选择

[英]Why Selected value get deselect when I reload table view in objective c

I am new in iOS and I am facing problem in custom table view.我是 iOS 新手,在自定义表格视图中遇到问题。 I am using custom table view cell我正在使用自定义表格视图单元格

AuditTableviewcell.h
{
    NSString *ActualString;
    IBOutlet UIButton *infobtn;
    UITextField * alertTextField;
    UITextView *textView1;

    UILabel *lbl;
}

-(IBAction)passbtnClick:(id)sender;
-(IBAction)failbtnClick:(id)sender;
-(IBAction)wipbtnClick:(id)sender;
-(IBAction)nabtnClick:(id)sender;
-(IBAction)infobtnClick:(id)sender;

@property(nonatomic,strong)IBOutlet UILabel *audittitlelbl;
@property(nonatomic,strong)IBOutlet UILabel *listlbl;

@property(nonatomic,strong) IBOutlet UILabel *passlbl;
@property(nonatomic,strong) IBOutlet UILabel *faillbl;
@property(nonatomic,strong) IBOutlet UILabel *warninglbl;
@property(nonatomic,strong) IBOutlet UILabel *nalbl;
@property(nonatomic,strong) IBOutlet UILabel *actuallbl;
@property(nonatomic,strong) IBOutlet UILabel *nameidlbl;
@property(nonatomic,strong) IBOutlet UILabel *remarklbl;

@property(nonatomic,strong) IBOutlet UIButton *passbtn;
@property(nonatomic,strong) IBOutlet UIButton *failbtn;
@property(nonatomic,strong) IBOutlet UIButton *wipbtn;
@property(nonatomic,strong) IBOutlet UIButton *nabtn;

AuditTableviewcell.m AuditTableviewcell.m

@synthesize audittitlelbl,listlbl,passbtn,nabtn,passlbl,faillbl,warninglbl,nalbl,actuallbl,failbtn,wipbtn,nameidlbl;
- (void)awakeFromNib {

    passbtn.layer.cornerRadius = passbtn.bounds.size.width / 2.0;// this value vary as per your desire
    passbtn.clipsToBounds = YES;

    failbtn.layer.cornerRadius = failbtn.bounds.size.width / 2.0;// this value vary as per your desire
    failbtn.clipsToBounds = YES;

    wipbtn.layer.cornerRadius = wipbtn.bounds.size.width / 2.0;// this value vary as per your desire
    wipbtn.clipsToBounds = YES;

    nabtn.layer.cornerRadius = nabtn.bounds.size.width / 2.0;// this value vary as per your desire
    nabtn.clipsToBounds = YES;

    infobtn.layer.cornerRadius = infobtn.bounds.size.width / 2.0;// this value vary as per your desire
    [[infobtn layer] setBorderWidth:1.0f];
    infobtn.layer.borderColor =[[UIColor blueColor] CGColor];
    infobtn.clipsToBounds = YES;

    passlbl.hidden=YES;
    faillbl.hidden=YES;
    warninglbl.hidden=YES;
    nalbl.hidden=YES;
    actuallbl.hidden=YES;
    nameidlbl.hidden=YES;

    // Initialization code
}
- (void)textViewDidEndEditing:(UITextView *)theTextView
{
    if (![textView1 hasText]) {
        lbl.hidden = NO;
    }
}

- (void) textViewDidChange:(UITextView *)textView
{
    if(![textView hasText]) {
        lbl.hidden = NO;
    }
    else{
        lbl.hidden = YES;
    }  
}


-(IBAction)passbtnClick:(id)sender
{
    passbtn.backgroundColor=[UIColor greenColor];
    failbtn.backgroundColor=[UIColor lightGrayColor];
    wipbtn.backgroundColor=[UIColor lightGrayColor];
    nabtn.backgroundColor=[UIColor lightGrayColor];

    actuallbl.text=passlbl.text;
    ActualString=actuallbl.text;
}
-(IBAction)failbtnClick:(id)sender
{
    passbtn.backgroundColor=[UIColor lightGrayColor];
    failbtn.backgroundColor=[UIColor redColor];
    wipbtn.backgroundColor=[UIColor lightGrayColor];
    nabtn.backgroundColor=[UIColor lightGrayColor];

    actuallbl.text=faillbl.text;
    ActualString=actuallbl.text;
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:ActualString forKey:@"ActualStringCustom"];

    UIAlertView *testAlert = [[UIAlertView alloc] initWithTitle:@"Fail!"
                                                        message:audittitlelbl.text
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Done", nil];
    textView1 = [UITextView new];
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,90.0, 34.0)];


    [lbl setText:@"Enter Remark"];
    [lbl setFont:[UIFont systemFontOfSize:12]];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setTextColor:[UIColor lightGrayColor]];
    textView1.delegate = self;

    [textView1 addSubview:lbl];

    [testAlert setValue: textView1 forKey:@"accessoryView"];

    [testAlert show];

}
-(IBAction)wipbtnClick:(id)sender
{
    passbtn.backgroundColor=[UIColor lightGrayColor];
    failbtn.backgroundColor=[UIColor lightGrayColor];
    wipbtn.backgroundColor=[UIColor orangeColor];
    nabtn.backgroundColor=[UIColor lightGrayColor];

    actuallbl.text=warninglbl.text;
    ActualString=actuallbl.text;


    UIAlertView *testAlert = [[UIAlertView alloc] initWithTitle:@"Warning!"
                                                        message:audittitlelbl.text
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Done", nil];
    textView1 = [UITextView new];
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,90.0, 34.0)];
     [lbl setText:@"Enter Remark"];
    [lbl setFont:[UIFont systemFontOfSize:12]];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setTextColor:[UIColor lightGrayColor]];
    textView1.delegate = self;

    [textView1 addSubview:lbl];

    [testAlert setValue: textView1 forKey:@"accessoryView"];

    [testAlert show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if(buttonIndex==0)
    {

    }
}
-(IBAction)nabtnClick:(id)sender
{
    passbtn.backgroundColor=[UIColor lightGrayColor];
    failbtn.backgroundColor=[UIColor lightGrayColor];
    wipbtn.backgroundColor=[UIColor lightGrayColor];
    nabtn.backgroundColor=[UIColor blueColor];
    actuallbl.text=nalbl.text;
    ActualString=actuallbl.text;

}

-(IBAction)infobtnClick:(id)sender
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"info" message:@"Information to be displayed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

ViewController.m视图控制器.m

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
            static NSString *STI=@"STI";
            AuditTableViewCell *cell = (AuditTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AuditTableViewCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
                cell.accessoryType=UITableViewCellAccessoryNone;
            }
            cell.audittitlelbl.text=[NSString stringWithFormat:@"%@",[idarray objectAtIndex:indexPath.row]];
            cell.nameidlbl.text=[NSString stringWithFormat:@"%@",[CheckpointNameIDArray objectAtIndex:indexPath.row]];
            cell.passlbl.text=[NSString stringWithFormat:@"%@",[Passarray objectAtIndex:indexPath.row]];
            cell.faillbl.text=[NSString stringWithFormat:@"%@",[Failarray objectAtIndex:indexPath.row]];
            cell.warninglbl.text=[NSString stringWithFormat:@"%@",[Warningarray objectAtIndex:indexPath.row]];
            cell.nalbl.text=[NSString stringWithFormat:@"%@",[NAarray objectAtIndex:indexPath.row]];


            [cell.passbtn addTarget:self action:@selector(btnQuantityPressedPass:) forControlEvents:UIControlEventTouchUpInside];
            [cell.failbtn addTarget:self action:@selector(btnQuantityPressedFail:) forControlEvents:UIControlEventTouchUpInside];
             [cell.wipbtn addTarget:self action:@selector(btnQuantityPressedWarning:) forControlEvents:UIControlEventTouchUpInside];
             [cell.nabtn addTarget:self action:@selector(btnQuantityPressedNA:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView.layer setBorderColor:[UIColor blackColor].CGColor];
            [cell.contentView.layer setBorderWidth:0.5f];

            return cell;
       }

//TODO: PassButton from Cell method

-(void)btnQuantityPressedPass:(UIButton *)sender
{
    AuditTableViewCell *cell = sender.superview.superview;
    NSString *String =cell.actuallbl.text;
    NSString *String2=cell.nameidlbl.text;
    NSString *FailString=@"";
    NSString *WarningString=@"";
    NSLog(@"String =%@",String);

    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:String forKey:@"ActualStringCustom"];
    [defaults setObject:String2 forKey:@"CheckPointNameID"];

    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

    //  NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    NSLog(@"Result =%@",results);

        ComplareArray=[devices valueForKey:@"checkpointid"];

        BOOL contains = [ComplareArray containsObject:String2];

        if(contains == NO)
        {
            if (self.device) {
                // Update existing device
                [device setValue:Audit forKey:@"auditnameId"];
                [device setValue:String forKey:@"checklistid"];
                [device setValue:String2 forKey:@"checkpointid"];
                [device setValue:FailString forKey:@"failreason"];
                [device setValue:WarningString forKey:@"warningreason"];
                [device setValue:AuditStartDate forKey:@"starttimedate"];
                [device setValue:userid forKey:@"userid"];

                NSError *error = nil;
                // Save the object to persistent store
                if (![context save:&error]) {
                    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
                }



            } else {
            // Create a new device
                NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
                [newDevice setValue:Audit forKey:@"auditnameId"];
                [newDevice setValue:String forKey:@"checklistid"];
                [newDevice setValue:String2 forKey:@"checkpointid"];
                [newDevice setValue:FailString forKey:@"failreason"];
                [newDevice setValue:WarningString forKey:@"warningreason"];
                [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
                [newDevice setValue:userid forKey:@"userid"];

                NSError *error = nil;
                // Save the object to persistent store
                if (![context save:&error]) {
                    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
                }
             }

        }
        else
        {
            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }

            ///
            NSManagedObjectContext *context = [self managedObjectContext];

            NSFetchRequest *request = [[NSFetchRequest alloc] init];
            [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

            //  NSError *error = nil;
            NSArray *results = [context executeFetchRequest:request error:&error];
            NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
            [favoritsGrabbed setValue:String forKey:@"checklistid"];
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
        }

}
//TODO: FailButton from Cell method

-(void)btnQuantityPressedFail:(UIButton *)sender
{
    AuditTableViewCell *cell = sender.superview.superview;
    NSString *String =cell.actuallbl.text;
    NSString *String2=cell.nameidlbl.text;
    NSLog(@"String =%@",String);
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:String forKey:@"ActualStringCustom"];
    [defaults setObject:String2 forKey:@"CheckPointNameID"];
    NSString *FailString=@"";
    NSString *WarningString=@"";

    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

    //  NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    NSLog(@"Result =%@",results);

    ComplareArray=[devices valueForKey:@"checkpointid"];

    BOOL contains = [ComplareArray containsObject:String2];

    if(contains == NO)
    {
        if (self.device) {
            // Update existing device
            [device setValue:Audit forKey:@"auditnameId"];
            [device setValue:String forKey:@"checklistid"];
            [device setValue:String2 forKey:@"checkpointid"];
            [device setValue:FailString forKey:@"failreason"];
            [device setValue:WarningString forKey:@"warningreason"];
            [device setValue:AuditStartDate forKey:@"starttimedate"];
            [device setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }

        } else {
            // Create a new device
            NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
            [newDevice setValue:Audit forKey:@"auditnameId"];
            [newDevice setValue:String forKey:@"checklistid"];
            [newDevice setValue:String2 forKey:@"checkpointid"];
            [newDevice setValue:FailString forKey:@"failreason"];
            [newDevice setValue:WarningString forKey:@"warningreason"];
            [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
            [newDevice setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
       }

    }
    else
    {
        NSError *error = nil;
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }

        ///
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

        //  NSError *error = nil;
        NSArray *results = [context executeFetchRequest:request error:&error];
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
        [favoritsGrabbed setValue:String forKey:@"checklistid"];
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }
    }

}
//TODO: WarningButton from Cell method

-(void)btnQuantityPressedWarning:(UIButton *)sender
{
    AuditTableViewCell *cell = sender.superview.superview;

    NSIndexPath *indexPath = [Audittable indexPathForCell:cell];
    CurrentIndexPath=indexPath.row;

    // NSLog(@"%@",cell.actuallbl.text);

    NSString *String =cell.actuallbl.text;
    NSString *String2=cell.nameidlbl.text;
    NSLog(@"String =%@",String);
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:String forKey:@"ActualStringCustom"];
    [defaults setObject:String2 forKey:@"CheckPointNameID"];

    NSString *FailString=@"";
    NSString *WarningString=@"";

    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;


    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

    //  NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    NSLog(@"Result =%@",results);

    ComplareArray=[devices valueForKey:@"checkpointid"];

    BOOL contains = [ComplareArray containsObject:String2];

    if(contains == NO)
    {
        if (self.device) {
            // Update existing device
            [device setValue:Audit forKey:@"auditnameId"];
            [device setValue:String forKey:@"checklistid"];
            [device setValue:String2 forKey:@"checkpointid"];
            [device setValue:FailString forKey:@"failreason"];
            [device setValue:WarningString forKey:@"warningreason"];
            [device setValue:AuditStartDate forKey:@"starttimedate"];
            [device setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
       } else {
            // Create a new device
            NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
            [newDevice setValue:Audit forKey:@"auditnameId"];
            [newDevice setValue:String forKey:@"checklistid"];
            [newDevice setValue:String2 forKey:@"checkpointid"];
            [newDevice setValue:FailString forKey:@"failreason"];
            [newDevice setValue:WarningString forKey:@"warningreason"];
            [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
            [newDevice setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
        }
    }
    else
    {
        NSError *error = nil;
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }

        ///
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

        //  NSError *error = nil;
        NSArray *results = [context executeFetchRequest:request error:&error];
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
        [favoritsGrabbed setValue:String forKey:@"checklistid"];
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }
    }
}

//TODO: NAButton from Cell method

-(void)btnQuantityPressedNA:(UIButton *)sender
{
    AuditTableViewCell *cell = sender.superview.superview;
    // NSLog(@"%@",cell.actuallbl.text);

    NSString *String =cell.actuallbl.text;
     NSString *String2=cell.nameidlbl.text;
    NSLog(@"String =%@",String);
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:String forKey:@"ActualStringCustom"];
    [defaults setObject:String2 forKey:@"CheckPointNameID"];

    NSString *FailString=@"";
    NSString *WarningString=@"";

    NSManagedObjectContext *context = [self managedObjectContext];
    NSError *error;


    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

    //  NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    NSLog(@"Result =%@",results);

    ComplareArray=[devices valueForKey:@"checkpointid"];

    BOOL contains = [ComplareArray containsObject:String2];

    if(contains == NO)
    {
        if (self.device) {
            // Update existing device
            [device setValue:Audit forKey:@"auditnameId"];
            [device setValue:String forKey:@"checklistid"];
            [device setValue:String2 forKey:@"checkpointid"];
            [device setValue:FailString forKey:@"failreason"];
            [device setValue:WarningString forKey:@"warningreason"];
            [device setValue:AuditStartDate forKey:@"starttimedate"];
            [device setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
       } else {
            // Create a new device
            NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"AuditPost" inManagedObjectContext:context];
            [newDevice setValue:Audit forKey:@"auditnameId"];
            [newDevice setValue:String forKey:@"checklistid"];
            [newDevice setValue:String2 forKey:@"checkpointid"];
            [newDevice setValue:FailString forKey:@"failreason"];
            [newDevice setValue:WarningString forKey:@"warningreason"];
            [newDevice setValue:AuditStartDate forKey:@"starttimedate"];
            [newDevice setValue:userid forKey:@"userid"];

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }
       }
    }
    else
    {
        NSError *error = nil;
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }

        ///
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"AuditPost" inManagedObjectContext:context]];

        //  NSError *error = nil;
        NSArray *results = [context executeFetchRequest:request error:&error];
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
        [favoritsGrabbed setValue:String forKey:@"checklistid"];
        // Save the object to persistent store
        if (![context save:&error]) {
            NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
        }
    }

}

As in the Image I select Pass button在图像中我选择通过按钮

在此处输入图片说明

But when I reload the table selected button get unselect但是当我重新加载表格选择按钮时取消选择

在此处输入图片说明

how can I get the selected value when I reload the table.Thanks in Advance!重新加载表格时如何获得选定的值。提前致谢!

To much code.... You should post only code related to the problem.太多的代码......你应该只发布与问题相关的代码。 My guess, you set the view only and don't have variable responsible for this.我的猜测是,您只设置了视图,而没有对此负责的变量。 When you reload table view you update the color and setup the default color.当您重新加载表格视图时,您会更新颜色并设置默认颜色。 Simple solution - create Model that represents each cell.简单的解决方案 - 创建代表每个单元格的模型。 This model knows which buttons are selected etc.该模型知道选择了哪些按钮等。

edited: Example编辑:示例

class Model {

    var name: String?
    var isButtonOneSelected = false
    var isButtonTwoSelected = false
    var isButtonThreeSelected = false
    ....

}

In ios table view reuse the cell for every row so it does happen.在 ios 表视图中,为每一行重用单元格,所以它确实发生了。 You use model class for manage selection .您使用模型类来管理选择。 I have add selectors on button on cell .And also example of reload table view.我在单元格上的按钮上添加了选择器。还有重新加载表视图的示例。 Please check below code.请检查以下代码。

//
//  ViewController.m

#import "ViewController.h"
#import "DataModel.h"
#import "MyTableViewCell.h"

@interface ViewController ()
{
    NSMutableArray *arrData;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    arrData = [[NSMutableArray alloc]init];

    // create 15 model and store in array
    for (int i =0; i<15; i++)
    {
        DataModel *model = [DataModel new];
        model.strSelected = @"";
        [arrData addObject:model];

    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  arrData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *cell = [self.tblView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    // tag add on buttons
    cell.btnPPressed.tag = indexPath.row;
    cell.btnFPressed.tag = indexPath.row;
    cell.btnWPressed.tag = indexPath.row;
    cell.btnNAPressed.tag = indexPath.row;

    //method add on buttons
    [cell.btnPPressed addTarget:self action:@selector(btnP:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnFPressed addTarget:self action:@selector(btnF:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnWPressed addTarget:self action:@selector(btnW:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnNAPressed addTarget:self action:@selector(btnNA:) forControlEvents:UIControlEventTouchUpInside];


    //background color change on button
    DataModel *model = [arrData objectAtIndex:indexPath.row];
    if([model.strSelected isEqualToString:@"P"])
    {
        cell.btnPPressed.backgroundColor = [UIColor redColor];
    }
   else if([model.strSelected isEqualToString:@"F"])
    {
        cell.btnFPressed.backgroundColor = [UIColor redColor];
    }
   else if([model.strSelected isEqualToString:@"W"])
   {
       cell.btnWPressed.backgroundColor = [UIColor redColor];
   }
   else if([model.strSelected isEqualToString:@"NA"])
   {
       cell.btnNAPressed.backgroundColor = [UIColor redColor];
   }
   else
   {
       cell.btnPPressed.backgroundColor = [UIColor darkGrayColor];
       cell.btnFPressed.backgroundColor = [UIColor darkGrayColor];
       cell.btnWPressed.backgroundColor = [UIColor darkGrayColor];
       cell.btnNAPressed.backgroundColor = [UIColor darkGrayColor];

   }


    return cell;
}


//buttons methods

-(void)btnP:(UIButton *)sender
{
    sender.backgroundColor = [UIColor redColor];
    DataModel *model = [arrData objectAtIndex:sender.tag];
    model.strSelected = @"P";

    //example reload table
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblView reloadData];
    });



}
-(void)btnF:(UIButton *)sender
{
    sender.backgroundColor = [UIColor redColor];
    DataModel *model = [arrData objectAtIndex:sender.tag];
    model.strSelected = @"F";

    //example reload table
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblView reloadData];
    });


}
-(void)btnW:(UIButton *)sender
{
    sender.backgroundColor = [UIColor redColor];
    DataModel *model = [arrData objectAtIndex:sender.tag];
    model.strSelected = @"W";


    //example reload table
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblView reloadData];
    });

}
-(void)btnNA:(UIButton *)sender
{
    sender.backgroundColor = [UIColor redColor];
    DataModel *model = [arrData objectAtIndex:sender.tag];
    model.strSelected = @"NA";


    //example reload table
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblView reloadData];
    });

}

@end


//  DataModel.h
#import <Foundation/Foundation.h>

@interface DataModel : NSObject
@property(nonatomic, strong)NSString *strSelected;

@end


//  MyTableViewCell.h
#import <UIKit/UIKit.h>

@interface MyTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UIButton *btnPPressed;
@property (strong, nonatomic) IBOutlet UIButton *btnFPressed;
@property (strong, nonatomic) IBOutlet UIButton *btnWPressed;
@property (strong, nonatomic) IBOutlet UIButton *btnNAPressed;

@end

You can either have a model or a mutable dictionary to represent selection of your buttons.您可以使用模型或可变字典来表示您对按钮的选择。

NSMutableDictionary *buttonSelection = [@{@"P_Button" : @"Selected",
                                          @"F_Button" : @"Selected",
                                          @"W_Button" : @"Selected",
                                          @"NA_Button" : @"Selected"} mutableCopy];

Inside your method cellForRowAtIndexPath .在你的方法cellForRowAtIndexPath里面。 You can simply use this dictionary for each cell to update:你可以简单地使用这个字典来更新每个单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *STI=@"STI";

        AuditTableViewCell *cell = (AuditTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];

        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AuditTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            cell.accessoryType=UITableViewCellAccessoryNone;
        }

        if ([[buttonSelection objectForKey:@"P_Button"] isEqualToString:@"Selected"]) {
            [cell.passbtn setSelected:YES];
        }

        return cell;
}

Apart from this, it's better to have use delegate pattern for your custom cell to get the functionality you want.除此之外,最好为您的自定义单元格使用委托模式以获得您想要的功能。 It can be done in the following way.可以通过以下方式完成。

@protocol CustomCellProtocol <NSObject>

- (void)passButtonSelected:(BOOL)selected forIndexPath:(NSIndexPath *)indexPath;

@end

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic, weak) id<CustomCellProtocol> cellDelegate;

@property (nonatomic) NSIndexPath *indexPath;

@end

In your @implementation or .m file of CustomCell, on click of button, do the following@implementation.m文件中,单击按钮,执行以下操作

- (void)passButtonSelected {

    [self.cellDelegate passButtonSelected:YES forIndexPath:self.indexPath];
}

Inside you cellForRowAtIndexPath method,在你的cellForRowAtIndexPath方法中,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *STI=@"STI";

        AuditTableViewCell *cell = (AuditTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];

        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AuditTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            cell.accessoryType=UITableViewCellAccessoryNone;
        }

        cell.indexPath = indexPath;
        cell.cellDelegate = self;            

        if ([[buttonSelection objectForKey:@"P_Button"] isEqualToString:@"Selected"]) {
            [cell.passbtn setSelected:YES];
        }

        return cell;
}

So, when you click button on your cell.因此,当您单击单元格上的按钮时。 You will get the following call in your tableview.m file.您将在tableview.m文件中收到以下调用。

- (void)passButtonSelected:(BOOL)selected forIndexPath:(NSIndexPath *)indexPath {

    NSMutableDictionary *statusDic = [[self.buttonStatusModelArray objectAtIndex:indexPath.row] mutableCopy];
   [statusDic setObject:(selected ? @"Selected" : @"NonSelected") forKey:@"P_Button"];

    [self.buttonStatusModelArray replaceObjectAtIndex:indexPath.row withObject:statusDic];
}

If you have any problems in implementing this, please let me know.如果您在实施过程中遇到任何问题,请告诉我。 Feel free to suggest edits to make this better :)请随时提出修改建议以使其更好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用按钮的情况下在视图控制器上获取自定义 TableViewCell 值并在目标 c 中重新加载表后设置它 - How to get custom TableViewCell value on view controller without using button and set it after reload table in objective c 当我滚动表格视图时,它删除了选定的项目-Objective-c - When I scroll table view it removed selected items - Objective-c 重新加载表视图数据并取消选择单元格 - Reload Table View Data and Deselect Cell 当我在viewcontroller上使用3视图时,它在目标c中变慢 - when i am using 3 view on viewcontroller it get slow in objective c 我选择时间后取消选择单元格 - Deselect cell after time when i selected 取消选择已通过编程选择的表格视图单元格 - Deselect a Table View Cell that has been selected programmatically 如何通过iOS Objective C中的appDelegate从另一个视图控制器重新加载表视图 - How to reload table view from another view controller via appDelegate in iOS Objective C 目标c-重新加载集合视图异步 - Objective c - Reload collection view async Objective C /C。当我尝试在IOS设备上获取Mac Adress时,我得到了错误的价值 - Objective C / C. I get wrong Value when i try to get Mac Adress on IOS device 如何使用Objective C获取Tableview选定的单元格UILabels值? - How to get Tableview selected cell UILabels Value using Objective C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM