I have a custom table view cell with slider and a label. I have created a property for the slider and label on my custom cell. I want to transfer the slider value to the label. This is what I tied:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *cellInfo = [[self.sections objectAtIndex:currentTab] objectAtIndex:indexPath.row];
HLMagnitudoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[cellInfo objectForKey:#"cell"] forIndexPath:indexPath];
UIImageView *radioIndicator = (UIImageView *)[cell.contentView viewWithTag:200];
radioIndicator.image = (currentBullet != indexPath.row) ? [UIImage imageNamed:#"RadioOff"] : [UIImage imageNamed:#"RadioOn"];
UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
av.backgroundColor = [UIColor clearColor];
av.opaque = NO;
av.image = [UIImage imageNamed:#"NewsSeparetor.png"];
cell.backgroundView = av;
cell.slider.maximumValue = 100;
cell.slider.minimumValue = 1;
cell.slider.continuous = TRUE;
cell.slider.tag = 1;
cell.slider.value = [cell.label.text intValue];
[cell.slider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
return cell;
}
- (void)sliderChanged:(UISlider *)slider
{
}
Create your sliders in the cells and set a tag value for each one:
eg:
slider.tag=1
The register a method to be called when the value is updated:
[slider addTarget:self action:#selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
Then in your method you will be able to get the values for sliders using the tag:
-(void)sliderChanged:(UISlider *)sender {
int tag = sender.tag;
if (tag ==1 ) //Update the label
slider1Label.text=[NSString strinWithFormat:#"%d",sender.value]
}
else if (tag == 2){
//Do something else
}
}
Related
I Want to Put CheckMarks in tableview when selecting array of dictionaries data.
Ex:- Array contains 10 Model Names(It is Dictionary), It contains SubModels
My problem is,When I select Submodel, ModelName automatically get CheckMark.
Now I Put CheckMarks for different models & sub Models but how we can put checkmarks based on SubModels.
My cellForRow method
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
UILabel *nameLbl = (UILabel*) [cell.contentView viewWithTag:11];
UILabel *code = (UILabel*) [cell.contentView viewWithTag:12];
UIButton *button = (UIButton*) [cell.contentView viewWithTag:13];
NSInteger index = indexPath.row;
NSDictionary *dictParent = [_data objectAtIndex:indexPath.section];
NSDictionary *dictItem = dictParent;
if (indexPath.row > 0)
{
// If its not the first row in the section, assume the row is a child row.
NSArray *arrChildren = [dictParent objectForKey:#"ChildProductModels"];
// Get child row info
dictItem = [arrChildren objectAtIndex:indexPath.row ];
}
nameLbl.text = [dictItem objectForKey:#"Name"];
code.text = [dictItem objectForKey:#"Code"];
// To display checkmark for selected value
if (_selectedarray.count == _rowdata.count)
{
imagebutton.hidden=NO;
[headerArray removeAllObjects];
[headerArray addObject:#"1"];
UIImage *btnImage = [UIImage imageNamed:#"ic_floating_done_#1x"];
[button setImage:btnImage forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor colorWithRed:0/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]];
}
else if ([_selectedarray containsObject:[_rowdata objectAtIndex:index]] )
{
imagebutton.hidden =NO;
[headerArray removeAllObjects];
[headerArray addObject:#"1"];
UIImage *btnImage = [UIImage imageNamed:#"ic_floating_done_#1x"];
[button setImage:btnImage forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor colorWithRed:0/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]];
}
else
{
imagebutton.hidden=YES;
cell.accessoryType=UITableViewCellAccessoryNone;
UIImage *btnImage = [UIImage imageNamed:#""];
[button setImage:btnImage forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor whiteColor]];
}
From the above code I am Able to put checkmarks for multiple selection.Please give some idea (OR) example for My problem
(
{
ChildProductModels = (
{
Code = "LB3/7-002";
Name = "With transport apron 4.5 M";
ParentChildType = C;
ParentID = PMD000001;
ProductID = PRD000004;
ProductModelID = PMD000003;
},
{
Code = "LB3/7-003";
Name = "With Magnetic Roller";
ParentChildType = C;
ParentID = PMD000001;
ProductID = PRD000004;
ProductModelID = PMD000004;
}
);
Code = "LB3/7";
Name = "Mixing Bale Opener LB3/7";
ParentChildType = P;
ParentID = "<null>";
ProductID = PRD000004;
ProductModelID = PMD000001;
},
{
ChildProductModels = (
{
Code = "LB7/4-001";
Name = "With Beater";
ParentChildType = C;
ParentID = PMD000005;
ProductID = PRD000004;
ProductModelID = PMD000006;
}
);
Code = "LB7/4";
Name = "UNIMIX MODEL LB7/4";
ParentChildType = P;
ParentID = "<null>";
ProductID = PRD000004;
ProductModelID = PMD000005;
}
)
Above I put my array of dictionaries
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
Header *headerView = [tableView dequeueReusableCellWithIdentifier:#"HeaderView"];
UILabel *name = (UILabel*) [headerView.contentView viewWithTag:2];
UILabel *code = (UILabel*) [headerView.contentView viewWithTag:4];
name.text = [_data[section] valueForKey:#"Name"] ;
code.text=[_data[section] valueForKey:#"Code"] ;
imagebutton=(UIButton*)[headerView.contentView viewWithTag:3];
UIImage *btnImage = [UIImage imageNamed:#""];
[imagebutton setImage:btnImage forState:UIControlStateNormal];
[imagebutton setBackgroundColor:[UIColor whiteColor]];
if(headerArray.count>0)
{
if([headerArray containsObject:#"0"])
{
UIImage *btnImage = [UIImage imageNamed:#""];
[imagebutton setImage:btnImage forState:UIControlStateNormal];
[imagebutton setBackgroundColor:[UIColor whiteColor]];
}
else
{
UIImage *btnImage = [UIImage imageNamed:#"ic_floating_done_#1x"];
[imagebutton setImage:btnImage forState:UIControlStateNormal];
[imagebutton setBackgroundColor:[UIColor colorWithRed:0/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]];
}
}
UIButton *btn=(UIButton*)[headerView.contentView viewWithTag:1];
[btn addTarget: self
action: #selector(buttonClicked:)
forControlEvents: UIControlEventTouchUpInside];
return headerView;
}
-(void)buttonClicked:(id)sender
{
if(imagebutton.currentImage == [UIImage imageNamed:#""] )
{
UIImage *btnImage = [UIImage imageNamed:#"ic_floating_done_#1x"];
[imagebutton setImage:btnImage forState:UIControlStateNormal];
[imagebutton setBackgroundColor:[UIColor colorWithRed:0/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]];
}
else
{
UIImage *btnImage = [UIImage imageNamed:#""];
[imagebutton setImage:btnImage forState:UIControlStateNormal];
[imagebutton setBackgroundColor:[UIColor whiteColor]];
}
}
In above My viewForHeader method
My TableviewdidSelect Method
selectedIndex = indexPath.row;
NSNumber *num=[NSNumber numberWithInteger:indexPath.section];
if (!_selectedarray)
{
imagebutton.hidden=YES;
[headerArray addObject:#"0"];
_selectedarray = [[NSMutableArray alloc] init];
}
if(![_selectedarray containsObject:[_rowdata objectAtIndex:selectedIndex]])
{
imagebutton.hidden=NO;
[headerArray removeAllObjects];
[headerArray addObject:#"1"];
[_selectedarray addObject:[_rowdata objectAtIndex:selectedIndex]];
[dataArray addObject:[_rowdata objectAtIndex:selectedIndex]];
[selectedSection addObject:num];
}
else
{
imagebutton.hidden=YES;
[headerArray addObject:#"0"];
[_selectedarray removeObject:[_rowdata objectAtIndex:selectedIndex]];
[dataArray removeObject:[_rowdata objectAtIndex:selectedIndex]];
}
[tableView reloadData];
Im utilizing the "tag" attribute to easily access the Section header in the TableView.
Something like this:
- (void)loadData {
myData = #[
#{
#"Code":#"LB3/7",
#"Name":#"Mixing Bale Opener LB3/7",
#"ParentChildType":#"P",
#"ParentID":[NSNull null],
#"ProductID":#"PRD000004",
#"ProductModelID":#"PMD000001",
#"ChildProductModels":#[
#{
#"Code":#"LB3/7-002",
#"Name":#"With transport apron 4.5 M",
#"ParentChildType":#"C",
#"ParentID":#"PMD000001",
#"ProductID":#"PRD000004",
#"ProductModelID":#"PMD000003"
},
#{
#"Code":#"LB3/7-003",
#"Name":#"With Magnetic Roller",
#"ParentChildType":#"C",
#"ParentID":#"PMD000001",
#"ProductID":#"PRD000004",
#"ProductModelID":#"PMD000004"
}
]
},
#{
#"Code":#"LB7/4",
#"Name":#"UNIMIX MODEL LB7/4",
#"ParentChildType":#"P",
#"ParentID":[NSNull null],
#"ProductID":#"PRD000004",
#"ProductModelID":#"PMD000005",
#"ChildProductModels":#[
#{
#"Code":#"LB7/4-001",
#"Name":#"With Beater",
#"ParentChildType":#"C",
#"ParentID":#"PMD000005",
#"ProductID":#"PRD000004",
#"ProductModelID":#"PMD000006"
}
]
}
];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
arrSelectedRows = [NSMutableArray new];
myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
myTableView.dataSource = self;
myTableView.delegate = self;
[self.view addSubview: myTableView];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSDictionary *dictParent = [myData objectAtIndex:section];
// Create section header (replace with custom UIView)
UILabel *lblSectionHeader = [UILabel new];
lblSectionHeader.tag = section + 100; // Set tag, so we can access it later
lblSectionHeader.text = [dictParent objectForKey:#"Name"];
return lblSectionHeader;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return myData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dictParent = [myData objectAtIndex:section];
NSArray *arrChildren = [dictParent objectForKey:#"ChildProductModels"];
return arrChildren.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellId"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cellId"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
// Get the parent item
NSDictionary *dictParent = [myData objectAtIndex:indexPath.section];
// Get children
NSArray *arrChildren = [dictParent objectForKey:#"ChildProductModels"];
// Get child row info
NSDictionary *dictItem = [arrChildren objectAtIndex:indexPath.row];
cell.textLabel.text = [dictItem objectForKey:#"Name"];
cell.detailTextLabel.text = [dictItem objectForKey:#"Code"];
// Make sure accessory type is set when the rows are populated
if ([arrSelectedRows containsObject:indexPath]) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
} else {
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([arrSelectedRows containsObject:indexPath]) {
// If the selected row was already selected, deselect it
[arrSelectedRows removeObject:indexPath];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[cell setAccessoryType:UITableViewCellAccessoryNone];
// Check if all children are deselected
NSInteger numRowsInSection = [tableView numberOfRowsInSection:indexPath.section];
BOOL areChildrenDeselected = true;
for (NSInteger i = 0; i < numRowsInSection; i++) {
NSIndexPath *childIndexPath = [NSIndexPath indexPathForRow:i inSection:indexPath.section];
if ([arrSelectedRows containsObject:childIndexPath]) {
areChildrenDeselected = false;
}
}
// Get the section header
UILabel *lblSectionHeader = (UILabel *)[tableView viewWithTag: 100 + indexPath.section];
if (areChildrenDeselected) {
lblSectionHeader.textColor = [UIColor blackColor];
} else {
lblSectionHeader.textColor = [UIColor blueColor];
}
} else {
// If the selected row wasnt selected, select it
[tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[arrSelectedRows addObject:indexPath];
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
// Get section header
UILabel *lblSectionHeader = (UILabel *)[tableView viewWithTag: 100 + indexPath.section];
lblSectionHeader.textColor = [UIColor blueColor];
}
}
...which results in something like this below, where the parent/section header is automatically set to blue when a child is selected.
To place check marks you can have an UIImageView at the appropriate place for the check mark.
And then you can maintain an array of selected cells, which will contain a boolean, isSelected(or whatever seems good to you).
Then once the user selected a cell, in didSelect delegate method. Just reload you cell by reloadRows:atIndexPath.
I have added one custom button on tableview cell and everything is ok.
But here my main requirement is when I click that button for the "first time" which is added on table view cell, then the button background color needs to change(to red) and when I click the second time the button, the previous color needs to be displayed(back to white)
My code:
#import "ViewController2.h"
#interface ViewController2 ()
{
NSArray * Mainarray;
UITableView * MaintableView;
UIImageView * accessoryView;
UIButton *button;
BOOL tapped;
}
#end
#implementation ViewController2
- (void)viewDidLoad
{
[super viewDidLoad];
tapped = NO;
Mainarray = [[NSArray alloc]initWithObjects:#"Ram",#"Rama",#"Rakesh",#"Ranjith", nil];
self.view.backgroundColor = [UIColor darkGrayColor];
MaintableView = [[UITableView alloc]init];
MaintableView.translatesAutoresizingMaskIntoConstraints = NO;
MaintableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
MaintableView.dataSource=self;
MaintableView.delegate=self;
MaintableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[MaintableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
[self.view addSubview:MaintableView];
NSDictionary * views = NSDictionaryOfVariableBindings(MaintableView);
NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[MaintableView]-0-|" options:0 metrics:nil views:views];
NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[MaintableView]-0-|"options:0 metrics:nil views:views];
[self.view addConstraints:horizentalConstraint];
[self.view addConstraints:verticalConstraint];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return Mainarray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [Mainarray objectAtIndex:indexPath.row];
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
button.backgroundColor = [UIColor whiteColor];
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
-(void)aMethod :(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:MaintableView];
NSIndexPath *indexPath1 = [MaintableView indexPathForRowAtPoint:buttonPosition];
NSInteger variable = indexPath1.row;
NSLog(#"ok it is %ld",(long)variable);
if(button.tag == variable){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = YES;
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
#end
You can create an array in which u can store selected buttons.
Example:
var selectedButtons: [Bool] = [Bool](count: N, repeatedValue: false)
In your cellForRowAtIndexPath:
if selectedButtons[indexPath.row] {
yourButton.backgroundColor = UIColor.redColor()
} else {
yourButton.backgroundColor = UIColor.whiteColor()
}
Then in your tableView didSelectRowAtIndexPath you can say:
selectedButtons[indexPath.row] = true
tableView.reloadData()
Sorry, my code is in Swift but it isn't hard to convert it to Obj-C.
Give your button a tag value in the cellForRowIndexpath method:
button.tag=indexPath.row;
and in your view did load, make the BOOL as a property in your .m file and make it accessible for the whole class
BOOL tapped =NO;
and then in your button action method:
-(IBAction)buttonMethod:(id)sender{
if(sender.tag==0){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = !tapped;
}
}
Please try below code. Hope this is work for you.
-(void)aMethod:(id)sender
{
UIButton *btn = (UIButton *)sender;
if ([btn.backgroundColor isEqual:[UIColor redColor]]) {
btn.backgroundColor = [UIColor whiteColor];
}
else{
btn.backgroundColor = [UIColor redColor];
}
}
Thanks.. :)
I tried to get the solution for your question and finally i got.
First you have to change Button Type RECT to CUSTOM in Attributes Inspector.Because in button type RECT the default background color of button is BLUE.So when you click for changing the color of the button, it comes actual color(it changes to your required color) with BLUE color.So you need to set the button type as CUSTOM.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayButtonData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
if (customCell==nil)
{
customCell = [nib objectAtIndex:0];
}
customCell.labelArrayListsNames.text = [NSString stringWithFormat:#"%#",[arrayButtonData objectAtIndex:indexPath.row]];
customCell.imageCircleRound.tag = indexPath.row;
NSLog(#"The custom cell button tag is - %ld",(long)customCell.imageCircleRound.tag);
NSLog(#"The label text is - %#",customCell.labelArrayListsNames.text);
[customCell.imageCircleRound addTarget:self action:#selector(cellCustomButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];;
return customCell;
}
-(void)cellCustomButtonClicked:(UIButton *)sender
{
if(![sender isSelected])
{
[sender setBackgroundColor:[UIColor redColor]];
sender.Selected = YES;
}
else
{
[sender setBackgroundColor:[UIColor whiteColor]];
sender.Selected = NO;
}
}
It works fine.Check it.
enter code hereFor such problem use array of dictionary for tableview datasource array. Like this
NSMutableDictionary *datadict = [[NSMutableDictionary alloc] init];
[datadict setObject:#"Your title" forKey:#"Title"];
[datadict setObject:#"N" forKey:#"isSelected"];
[mainArray addObject: datadict]
put this code in loop for all your titles and N for isSelected key first time.
then you tableview method specially cellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [[mainArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
if([[[mainArray objectAtIndex:indexPath.row] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
button.backgroundColor = [UIColor redColor];
}
else
{
button.backgroundColor = [UIColor whiteColor];
}
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
Then in your button action should be like
-(IBAction)aMethod :(id)sender
{
UIButton *selectedBtn = (UIButton *)sender;
if([[[mainArray objectAtIndex:[sender tag]] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
selectedBtn.backgroundColor = [UIColor whiteColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"N" forKey:#"isSelected"];
}
else
{
selectedBtn.backgroundColor = [UIColor redColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"Y" forKey:#"isSelected"];
}
}
you can also reload table in button action to see effect. It is good code technique to maintain multiple row selection and where data is large and realtime. By this we can get all selected rows whenever we needed on any event.
I have this collapsable UITableView where there is a UITextField and a UIButton in the last cell in each table section. I would like to send the text in the UITextField to the function that is called by the UIButton that is next to it in the same cell, but I am baffled in how to achieve this. Thanks in advance for the help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([self tableView:_tableView canCollapseSection:indexPath.section])
{
int num = 1;
if (self.chat[indexPath.section - 1][#"num"] != nil)
num = [self.chat[indexPath.section - 1][#"num"] intValue] + 1;
if (!indexPath.row)
{
cell.textLabel.text = self.chat[indexPath.section - 1][#"msg"]; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else if (indexPath.row < num && indexPath.row >= 1)
{
cell.textLabel.text = self.chat[indexPath.section - 1][key];
cell.accessoryView = nil;
}
else
{
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:field];
cell.accessoryView = nil;
}
}
else
{
cell.accessoryView = nil;
cell.textLabel.text = #"Normal Cell";
}
return cell;
}
Give some unique tag to textfield and button by below way:
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
self.sendButton.tag = indexPath.section *1000 + indexPath.row;
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
field.tag = self.sendButton.tag + 1;
[cell addSubview:field];
cell.accessoryView = nil;
Now on button event,
-(void) sendReply:(UIButton *)sender
{
UITextField *field = [YOOUR_TABLE_VIEW viewWithTag:sender.tag + 1];
//Do you coding here
}
Make a Custom UITableViewCell that has uitextfield and a button on it and make a protocol/delegate of that custom uitableviewcell you've created.. so you can have more control of your code and the event of your button in the future..
check this tutorial: http://www.codigator.com/tutorials/ios-uitableview-tutorial-custom-cell-and-delegates/
cheers
For this,
In cellForRowAtIndexPath: method where you are allocating the send button add one line just to give some identifier to send button as below,
[self.sendButton setAccessibilityIdentifier:[NSString stringWithFormat:#"%d#%d",indexPath.row,indexPath.section]];
Now, in sendReply: method,
//First get the row and section information
NSString *str=[sender accessibilityIdentifier];
NSArray *arr=[str componentsSeparatedByString:#"#"];
//Get the index path
NSIndexPath *iRowId =[NSIndexPath indexPathForRow:[[arr objectAtIndex:0] intValue] inSection:[arr objectAtIndex:1] intValue]];
//get the cell
UITableViewCell *objCell=(UITableViewCell*)[tblviwBasketCell cellForRowAtIndexPath:iRowId];
Now objCell will be the cell in which you have added the button and text view. so get the subviews of objCell and access the textfield to get the text.
As you say, there is a text field in each section. You should set the tag of your UIButton and UITextField same as indexPath.section.
Then, in the target method, use this tag value to get the relevant cell from the relevant section, and iterate over it's subviews to get your textField.
In the target method, you should do something like this:
- (void) sendReply:(id)sender {
int section = [(UIButton*)sender tag];
int row = [myTableView numberOfRowsInSection:section] - 1;//assuming it is the last cell in the section that contains your textField.
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [myTableView cellForRowAtIndexPath:indexPath];
for (UIView* vu in cell.subviews) {
if ([vu isKindOfClass:[UITextField class]]) {
NSString* textString = [(UITextField*)vu text];
//perform any tasks you want with the text now
}
}
}
You can simply use viewWithTag:, since it does an iterative search, but all the extra code is to avoid iterating over all the cells before reaching your relevant cell.
When I search in table view, it gives correct array, I am using NSPredicate to filter array. Even while debugging I came to know, it goes to cellForRowAtIndexPath and label is having data and everything is proper but as result there is only plain white default table view is shown, not the table which should be, after searching.
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
preferredCustomCell *mycell = (preferredCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIView *backgroundView = [[UIView alloc] initWithFrame:mycell.selectedBackgroundView.frame];
[backgroundView setBackgroundColor:[UIColor colorWithRed:189/255.f green:189/255.f blue:189/255.f alpha:0.25]];
[mycell setSelectedBackgroundView:backgroundView];
SearchbackView.hidden = YES;
// Configure the cell...
if (mycell == nil) {
mycell = [[preferredCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
MyData *dealerData = Nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dealerData = [searchResults objectAtIndex:indexPath.row];
} else {
dealerData = [cellData objectAtIndex:indexPath.row];
}
dealerInfo = [NSString stringWithFormat:#"%#\n%#\n%#%#%#%#%#\n%#\n%#", dealerData.businessName, dealerData.address, dealerData.city,#", ", dealerData.state, #", ", dealerData.zip, dealerData.phone, dealerData.email]; // data.address;
mycell.dealerInfoLbl.text = dealerInfo;
mycell.dealerInfoLbl.numberOfLines = 0;
mycell.selectDealerBtn.tag = indexPath.row;
// Assign our own background image for the cell
UIImage *background = [UIImage imageNamed:#"selectedCell"];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
mycell.selectedBackgroundView = cellBackgroundView;
mycell.lblPreferred.hidden = YES;
if (mycell.selectDealerBtn.tag==btnTag) {
if (selectDealer==true) {
[mycell.selectDealerBtn setImage:[UIImage imageNamed:#"selectedDealer"] forState:UIControlStateNormal];
[mycell.selectDealerBtn setTitle:#"Select" forState:UIControlStateNormal];
mycell.selectDealerBtn.imageEdgeInsets = UIEdgeInsetsMake(6, 16, 26, 17);
mycell.selectDealerBtn.titleEdgeInsets = UIEdgeInsetsMake(32,-66, 0, 10);
mycell.lblPreferred.hidden = NO;
}
}
else{
[mycell.selectDealerBtn setImage:[UIImage imageNamed:#"N99-selectDealerBtn"] forState:UIControlStateNormal];
[mycell.selectDealerBtn setTitle:#" " forState:UIControlStateNormal];
mycell.lblPreferred.hidden = YES;
}
return mycell;
When I scroll UITableView my tableview cells automatically uncheck. But when I press done button it give me selected rows I can't understand why is this happening.
My Tableview code is as below :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
idArray = [[NSMutableArray alloc]init];
NSLog(#"Cat Array : %#",catArray);
isSelectAllBtnClicked = NO;
serviceArray = [[NSArray alloc]initWithObjects:#"Anal", #"Cuffed", #"Foreplay", #"Masturbation", #"Scat", #"Blindfolded",#"Deep throat", #"French Kissing", #"Missionary", #"Shower for 2", #"Bottom", #"Dinner Date", #"Full Bondage", #"Mutual Masturbation", #"Spanking", #"Boy on Boy", #"Dirty Talk",#"Girl on Girl", #"On top", #"Strap on", #"Choking", #"Doggy", #"Girlfriend Experience", #"Oral", #"Striptease", #"CIM", #"Dominate", #"Golden Shower",#"Oral Mutual", #"Submissive", #"COB", #"Fantasy", #"Kissing", #"Overnight", #"Top", #"COF", #"Fetish", #"Light Bondage", #"Rim me",#"Touching", #"Couples", #"Fisting", #"Lingerie", #"Rim you", #"Toys for me", #"Cuddling", #"Foot fetish", #"Massage", #"Role Play", #"Toys for you", nil];
[myTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"reuseIdentifier";
UITableViewCell *cell = [[UITableViewCell alloc]init];
if (cell != NULL)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
//NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"]forState:UIControlStateNormal];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"]forState:UIControlStateNormal];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count;
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
count = [serviceArray count];
}
else
{
count = [catArray count];
}
return count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
thanks in advance.
when ever you scroll the table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method executes and you have not mentioned any condition by which it can be judged that this row was previously selected or not. you have to insert a condition along with indexPath.row and check whether it is prviously selected or not
try like this ,when you scroll the tableview every time isSelectAllBtnClicked value is 0 that's why every time button changed.
when you scroll the table every time new cell created try to avoid that one
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
}
}