uitableview: в той же строке выбранная кнопка должна быть проверена, а оставшиеся кнопки должны быть сняты автоматически - PullRequest
0 голосов
/ 27 июня 2018

Я делаю форму обратной связи, используя UITableview, используя пользовательский флажок для выбора. В UITableviewcell я поместил четыре статические кнопки для таких опций, как, Очень Хорошо , Хорошо , Среднее , Ниже среднего .

Что я хочу, так это то, что я хочу выбрать только одну кнопку, отмеченную подряд, если я выберу другую кнопку, отмеченную автоматически, предыдущая выбранная кнопка должна быть не отмечена.

Пример: в той же строке предположим, что если я выберу Очень хорошо Сначала я снова выбрал Среднее , предыдущее выбранное Очень хорошо должно быть отключено.

Проверьте мой код ниже для справки:

Это в cellforrowatindexpath

[cell.R1_BTN setImage:[UIImage imageNamed:@"Touch_G.png"] forState:UIControlStateNormal];
[cell.R1_BTN addTarget:self action:@selector(BtnClicked:) forControlEvents:UIControlEventTouchUpInside]; 
cell.R1_BTN.tag=1;

Нажмите здесь событие ..

-(void)BtnClicked:(id)sender
{
//Need Code Here..
}

shared my screen once :

обновлен код для справки ..

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   return [GNM count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   return  [GNM objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if ([[NM objectAtIndex:section] isKindOfClass:[NSArray class]])
   {
     return [[NM objectAtIndex:section] count];
   }
   else
   {
     return 1;
   }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 FeedBackFormTVC *cell = [FeedBack_TV dequeueReusableCellWithIdentifier:@"ListCell" forIndexPath:indexPath];

cell.FBName_LBL.text = [[NM objectAtIndex:indexPath.section] isKindOfClass:[NSArray class]]
? [[NM objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]
: [NM objectAtIndex:indexPath.section];

// below for assigning code action event..
....
....
...

}

Я пытался использовать теги, но я не получил то, что хочу, пожалуйста, помогите мне .. спасибо заранее.

Ответы [ 4 ]

0 голосов
/ 28 июня 2018

Поскольку вы не предоставили нам подробности ответа API, как было запрошено ранее, мы вынуждены использовать статическое значение. Пожалуйста, замените sectionTitleList & modelList из ответа API массива. Ниже приведен код, который будет использоваться для назначения ответа API для модели, созданной @ Gökhan Aydın.

sectionTitleList = @[@"RESERVATION",@"FRONT DESK",@"CASHIER",@"HOUSE KEEPING",@"COMMON"];
    modelList = @[
                 @[
                  @"Service Speed",
                  @"Good Service",
                  @"Confirmation quality",
                  @"Quick Service in Reservation"
                  ],
                 @[
                  @"Check In",
                  @"Happy on their Service",
                  @"Courtesey",
                  @"Quick Service at Checkin"
                  ],
                 @[
                  @"Front office & reception",
                  @"Overall Quality of Room",
                  @"Check",
                  @"Response time"
                  ],
                 @[
                  @"Room Decor",
                  @"Time taken to serveTime taken to serveTime taken t",
                  @"Bathroom",
                  @"Facilities in the Room",
                  @"Choice of menu",
                  @"Housekeeping",
                  @"Room Service"
                  ],
                 @[
                  @"Overall Comments",
                  @"Will you come back again"
                  ]
                 ];

        self.navigationItem.title = [modelList lastObject];
GNM = [sectionTitleList mutableCopy];
NM = [[NSMutableArray alloc]init];
for (NSArray *feedbacktitles in modelList) {
    if ([feedbacktitles isKindOfClass:[NSArray class]]) {
        __block NSMutableArray *tempArray = [NSMutableArray new];
        [feedbacktitles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
            FeedbackModel *model = [[FeedbackModel alloc]initWith:title withRangeMark:UNKNOWN];
            [tempArray addObject:model];
            if (idx ==  [feedbacktitles count] - 1 ) {
                *stop = TRUE;
                [self->NM addObject:tempArray];
                tempArray = [NSMutableArray new];
            }
        }];

    }
}

или простой цикл

for (NSArray *feedbacktitles in modelList) {
        NSLog(@"%@",feedbacktitles);
        NSMutableArray* rowStringArray = [NSMutableArray new];
        if ([feedbacktitles isKindOfClass:[NSArray class]]) {
            for(int i = 0; i < [feedbacktitles count]; i++) {
                NSString* rowTitle = [feedbacktitles objectAtIndex:i];
                FeedbackModel *model = [[FeedbackModel alloc]initWith:rowTitle withRangeMark:UNKNOWN];
                [rowStringArray addObject: model];
                if (i == [feedbacktitles count] - 1) {
                    [NM addObject: rowStringArray];
                    rowStringArray = [NSMutableArray new];
                }
            }
        }
    }
0 голосов
/ 27 июня 2018

да, это будет решением для вас, по крайней мере, я надеюсь, что так:)

Прежде всего создайте пользовательский файл кнопки .h как этот:

#import <UIKit/UIKit.h>

@interface CustomButton : UIButton

@property (assign) NSInteger sectionTag;
@property (assign) NSInteger rowTag;

@end

файл пользовательской кнопки .m, например:

#import "CustomButton.h"

@implementation CustomButton

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

затем я изменил несколько вещей в файле TableViewCell .h, например:

#import <UIKit/UIKit.h>
#import "CellModel.h"
#import "CustomButton.h"

@interface TableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet CustomButton *veryGoodButton;
@property (weak, nonatomic) IBOutlet CustomButton *goodButton;
@property (weak, nonatomic) IBOutlet CustomButton *averageButton;
@property (weak, nonatomic) IBOutlet CustomButton *belowAverageButton;
@property (weak, nonatomic) IBOutlet UILabel *itemLabel;

- (void)setupCellWithModel:(CellModel*)model;

@end

Файл TableViewCell .m, например:

#import "TableViewCell.h"

@implementation TableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setupCellWithModel:(CellModel *)model {

    if(model.range == VERY_GOOD) {
        self.veryGoodButton.backgroundColor = [UIColor greenColor];
    }
    else if(model.range == GOOD) {
        self.goodButton.backgroundColor = [UIColor blueColor];
    }
    else if(model.range == AVERAGE) {
        self.averageButton.backgroundColor = [UIColor yellowColor];
    }
    else if(model.range == BELOW_AVERAGE) {
        self.belowAverageButton.backgroundColor = [UIColor redColor];
    }

    [self.itemLabel setText:model.itemText];
}

- (void)prepareForReuse {
    [super prepareForReuse];
    self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
    self.goodButton.backgroundColor = [UIColor lightGrayColor];
    self.averageButton.backgroundColor = [UIColor lightGrayColor];
    self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}

и его .xib вот так:

enter image description here

с другой стороны, в файле CellModel .h есть только одно изменение:

#import <Foundation/Foundation.h>

typedef enum : NSInteger {
    UNKNOWN = 0,
    VERY_GOOD = 1,
    GOOD = 2,
    AVERAGE = 3,
    BELOW_AVERAGE = 4
}RangeMark;

@interface CellModel : NSObject

@property(nonatomic, assign)    RangeMark range;
@property(nonatomic, copy)      NSString* itemText;

- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range;

@end

и его файл .m так:

#import "CellModel.h"

@implementation CellModel

- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range {
    self = [super init];
    if(self) {
        self.itemText = itemText;
        self.range = range;
    }
    return self;
}

@end

наконец-то просмотрите .h файл контроллера, но .m вот так:

#import "ViewController.h"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
    NSMutableArray *modelList;
    NSMutableArray<NSString*> *sectionTitleList;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 600;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    sectionTitleList = [NSMutableArray<NSString*> new];
    [sectionTitleList addObject:@"RESERVATION"];
    [sectionTitleList addObject:@"FRONT DESK"];
    [sectionTitleList addObject:@"CASHIER"];
    [sectionTitleList addObject:@"HOUSE KEEPING"];

    modelList = [[NSMutableArray alloc] initWithCapacity: 4];

    [modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:@"Service Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Good Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Confirmation Quality" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Quick Service in Reservetion" withRangeMark:UNKNOWN],nil] atIndex:0];

    [modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:@"Check In" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Happy on Their Service" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Coutesey" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Quick Service at Check In" withRangeMark:UNKNOWN],nil] atIndex:1];

    [modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:@"Front Office & Reception" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Overall Quality of Room" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Check" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:@"Response Time" withRangeMark:UNKNOWN],nil] atIndex:2];

    [modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:@"Room Decor" withRangeMark:UNKNOWN],nil] atIndex:3];


//    [modelList addObject: [[CellModel alloc] initWith:@"Service Speed" withRangeMark:UNKNOWN]];
//    [modelList addObject: [[CellModel alloc] initWith:@"Good Speed" withRangeMark:UNKNOWN]];
//    [modelList addObject: [[CellModel alloc] initWith:@"Confirmation Quality" withRangeMark:UNKNOWN]];
//    [modelList addObject: [[CellModel alloc] initWith:@"Quick Service in Reservetion" withRangeMark:UNKNOWN]];

//    for (int i=0; i<5; i++) {
//        CellModel *cellModel = [[CellModel alloc] init];
//        cellModel.range = UNKNOWN;
//        cellModel.itemText = @"";
//        [modelList addObject:cellModel];
//    }
}

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

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

    TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    NSLog(@"section: %ld - row : %ld - item text : %@", (long)indexPath.section, (long)indexPath.row, ((CellModel*)[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).itemText);

    [cell setupCellWithModel:[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];

    ((CustomButton*)cell.veryGoodButton).rowTag = indexPath.row;
    ((CustomButton*)cell.veryGoodButton).sectionTag = indexPath.section;

    ((CustomButton*)cell.goodButton).rowTag = indexPath.row;
    ((CustomButton*)cell.goodButton).sectionTag = indexPath.section;

    ((CustomButton*)cell.averageButton).rowTag = indexPath.row;
    ((CustomButton*)cell.averageButton).sectionTag = indexPath.section;

    ((CustomButton*)cell.belowAverageButton).rowTag = indexPath.row;
    ((CustomButton*)cell.belowAverageButton).sectionTag = indexPath.section;

    [cell.veryGoodButton addTarget:self action:@selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];

    [cell.goodButton addTarget:self action:@selector(good:) forControlEvents:UIControlEventTouchUpInside];

    [cell.averageButton addTarget:self action:@selector(average:) forControlEvents:UIControlEventTouchUpInside];

    [cell.belowAverageButton addTarget:self action:@selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[modelList objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionTitleList.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
    [label setTextColor:[UIColor whiteColor]];
    NSString *string =[sectionTitleList objectAtIndex:section];

    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor darkGrayColor]];

    return view;
}

- (void) veryGood:(CustomButton*)sender {
    ((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = VERY_GOOD;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}

- (void) good:(CustomButton*)sender {
    ((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = GOOD;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}

- (void) average:(CustomButton*)sender {
    ((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = AVERAGE;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}

- (void) belowAverage:(CustomButton*)sender {
    ((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = BELOW_AVERAGE;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}

- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
    TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell prepareForReuse];
    [cell setupCellWithModel:cellModel];
}

@end

Я думаю, что это будет хорошо работать для вас. Просто измените часть массива init в коде на динамическую:)

Последнее появление:

enter image description here

0 голосов
/ 28 июня 2018
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 600;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    sectionTitleList = [NSMutableArray<NSString*> new];
    for (NSString* sectionTitle in yourSectionResponseArray) {
        [sectionTitleList addObject: sectionTitle];
    }

    modelList = [[NSMutableArray alloc] initWithCapacity: [sectionTitleList count]];

    //your row title array has to be 2D array.
    for(int i = 0; i < [sectionTitleList count]; i++) {
        NSMutableArray* rowStringArray = [NSMutableArray new];
        for(NSString* rowTitle in [your2DRowResponseArray objectAtIndex:i]) {
             [rowStringArray addObject: rowTitle];
        }
        [modelList insertObject: rowStringArray];
    } 
}

Может быть, это может вам помочь.

0 голосов
/ 27 июня 2018

Я думаю, что вы должны использовать модель, чтобы установить для UITableViewCell. Файл вашей модели .h, например:

#import <Foundation/Foundation.h>

typedef enum : NSInteger {
    UNKNOWN = 0,
    VERY_GOOD = 1,
    GOOD = 2,
    AVERAGE = 3,
    BELOW_AVERAGE = 4
}RangeMark;

@interface CellModel : NSObject

@property(nonatomic, assign)    RangeMark range;

@end

.m файл как:

#import "CellModel.h"

@implementation CellModel

@end

чем вам нужно инициализировать ячейку таблицы с файлом .xib: enter image description here

и его файл .h, например:

#import <UIKit/UIKit.h>
#import "CellModel.h"

@interface TableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIButton *veryGoodButton;
@property (weak, nonatomic) IBOutlet UIButton *goodButton;
@property (weak, nonatomic) IBOutlet UIButton *averageButton;
@property (weak, nonatomic) IBOutlet UIButton *belowAverageButton;

- (void)setupCellWithModel:(CellModel*)model;

@end

его .m файл как:

#import "TableViewCell.h"

@implementation TableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setupCellWithModel:(CellModel *)model {

    if(model.range == VERY_GOOD) {
        self.veryGoodButton.backgroundColor = [UIColor greenColor];
    }
    else if(model.range == GOOD) {
        self.goodButton.backgroundColor = [UIColor blueColor];
    }
    else if(model.range == AVERAGE) {
        self.averageButton.backgroundColor = [UIColor yellowColor];
    }
    else if(model.range == BELOW_AVERAGE) {
        self.belowAverageButton.backgroundColor = [UIColor redColor];
    }
}

- (void)prepareForReuse {
    [super prepareForReuse];
    self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
    self.goodButton.backgroundColor = [UIColor lightGrayColor];
    self.averageButton.backgroundColor = [UIColor lightGrayColor];
    self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}

@end

Наконец, ваш .h файл контроллера представления должен выглядеть так:

#import <UIKit/UIKit.h>
#import "TableViewCell.h"

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

и .m файл должны выглядеть так:

#import "ViewController.h"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
    NSMutableArray<CellModel*> *modelList;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.estimatedRowHeight = 600;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    modelList = [NSMutableArray<CellModel*> new];

    for (int i=0; i<50; i++) {
        CellModel *cellModel = [[CellModel alloc] init];
        cellModel.range = UNKNOWN;
        [modelList addObject:cellModel];
    }
}

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

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

    TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    [cell setupCellWithModel:[modelList objectAtIndex:indexPath.row]];

    cell.veryGoodButton.tag = indexPath.row;
    cell.goodButton.tag = indexPath.row;
    cell.averageButton.tag = indexPath.row;
    cell.belowAverageButton.tag = indexPath.row;

    [cell.veryGoodButton addTarget:self action:@selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];

    [cell.goodButton addTarget:self action:@selector(good:) forControlEvents:UIControlEventTouchUpInside];

    [cell.averageButton addTarget:self action:@selector(average:) forControlEvents:UIControlEventTouchUpInside];

    [cell.belowAverageButton addTarget:self action:@selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];

    return cell;

    return nil;
}

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

- (void) veryGood:(UIButton*)sender {
    [modelList objectAtIndex: sender.tag].range = VERY_GOOD;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}

- (void) good:(UIButton*)sender {
    [modelList objectAtIndex: sender.tag].range = GOOD;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}

- (void) average:(UIButton*)sender {
    [modelList objectAtIndex: sender.tag].range = AVERAGE;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}

- (void) belowAverage:(UIButton*)sender {
    [modelList objectAtIndex: sender.tag].range = BELOW_AVERAGE;
    [self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}

- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
    TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell prepareForReuse];
    [cell setupCellWithModel:cellModel];
}

@end

вот и все :) 1024 *

В конце приложение выглядит так:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...