Button in tableview footer is not getting called - ios

I have declared UIView and UIButton in the UIView
-(void)viewWillAppear:(BOOL)animated
{
footerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,300)];
UILabel *totallabel = [[UILabel alloc]initWithFrame:CGRectMake(50,5,320,40)];
totallabel.text = #"Grand Total =";
totallabel.font = [UIFont fontWithName:#"Lato-Regular" size:10];
totallabel.font = [UIFont systemFontOfSize:14];
[footerView addSubview:totallabel];
UILabel *lblRs = [[UILabel alloc]initWithFrame:CGRectMake(160,5,320,40)];
lblRs.text = #"Rs.";
lblRs.font = [UIFont fontWithName:#"Lato-Regular" size:10];
lblRs.font = [UIFont systemFontOfSize:14];
[footerView addSubview:lblRs];
totalcostlabel = [[UILabel alloc]initWithFrame:CGRectMake(190,5,320,40)];
totalcostlabel.font = [UIFont fontWithName:#"Lato-Regular" size:10];
totalcostlabel.font = [UIFont systemFontOfSize:14];
[footerView addSubview:totalcostlabel];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(70,50,150,40);
aButton.backgroundColor = [UIColor colorWithRed:119.0/225.0 green:49.0/255.0 blue:88.0/255.0 alpha:1.0];
[aButton setTitle:#"Checkout" forState:UIControlStateNormal];
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
aButton.titleLabel.font = [UIFont fontWithName:#"Lato-Regular" size:10];
[aButton addTarget:self action:#selector(btnChackOut:) forControlEvents:UIControlEventTouchUpInside];
[footerView addSubview:aButton ];
[self.tblView setTableFooterView:footerView];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return footerView;
}
- (void)btnChackOut:(UIButton *)sender {
NSLog(#"btn clicked");
}
When I click the Checkout button which is declared in my footer the click event is not performed and the action method is not getting called

I got the solution and now it has worked.Apply the below code.
in .h
#import "CustomCell.h"
-(IBAction)actionContinue:(id)sender;
#property (strong, nonatomic) IBOutlet UITableView *tblViewCart;
in .m
#synthesize tblViewCart;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
arrayImageCart = [[NSMutableArray alloc]initWithObjects:#"ios7.jpg",#"iphone_6.jpg",nil];
arrayPrice = [[NSMutableArray alloc]initWithObjects:#"Rs 60,000",#"Rs 55,000",nil];
arrayDescription = [[NSMutableArray alloc]initWithObjects:#"Made In China",#"Headquarter is in US",nil];
arrayOtherDetail = [[NSMutableArray alloc]initWithObjects:#"Black Color",#"White Color",nil];
arraySubTotal = [[NSMutableArray alloc]initWithObjects:#"Rs 60,000",#"Rs 55,000",nil];
arrayTotal = [[NSMutableArray alloc]initWithObjects:#"110000",nil];
arrayTotalCharges = [[NSMutableArray alloc]initWithObjects:#"2000",nil];
arrayYouPay = [[NSMutableArray alloc]initWithObjects:#"112000", nil];
self.tblViewCart.separatorColor = [UIColor clearColor];
}
// Button Action
-(IBAction)actionContinue:(id)sender
{
}
#pragma mark - UITableView Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 203;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section==0)
return arrayPrice.count;
else
return arrayYouPay.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"Reuse"];
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"CustomCell" owner:self options:nil];
if(indexPath.section==0)
{
cell = [nib objectAtIndex:0];
cell.imageViewCart.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",[arrayImageCart objectAtIndex:indexPath.row]]];
cell.lblPriceDetails.text = [NSString stringWithFormat:#"%#",[arrayPrice objectAtIndex:indexPath.row]];
cell.lblDescriptionAbtProduct.text = [NSString stringWithFormat:#"%#",[arrayDescription objectAtIndex:indexPath.row]];
cell.labelOtherDetails.text = [NSString stringWithFormat:#"%#",[arrayOtherDetail objectAtIndex:indexPath.row]];
cell.lblSubTotal.text = [NSString stringWithFormat:#"%#",[arraySubTotal objectAtIndex:indexPath.row]];
}
else
{
cell = [nib objectAtIndex:1];
cell.lblTotal.text = [NSString stringWithFormat:#"%#",[arrayTotal objectAtIndex:indexPath.row]];
cell.lblTotalCharges.text = [NSString stringWithFormat:#"%#",[arrayTotalCharges objectAtIndex:indexPath.row]];
cell.lblYouPay.text = [NSString stringWithFormat:#"%#",[arrayYouPay objectAtIndex:indexPath.row]];
}
return cell;
}
Create Custom Cell through NewFile->Source->CocoaTouchClass->Next>SubClassof:UITableViewCell,Class->CustomClass with CheckBox Also Create XIB file(This is for price details).
Then Inside CustomCell.xib file create another UITableViewCell and give name as CustomCell for Total Amount and Pay.

Can't called because you don't set a height for footer, just need set footer height like this:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 300;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 40;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 304, 40)];
footerView.backgroundColor = [UIColor whiteColor];
UIButton *add_member=[UIButton buttonWithType:UIButtonTypeCustom];
add_member.layer.borderWidth = 0.8;
add_member.layer.cornerRadius = 10;
add_member.layer.masksToBounds = YES;
add_member.layer.borderColor =[[UIColor lightGrayColor] CGColor];
add_member.layer.shadowColor = [[UIColor whiteColor] CGColor];
add_member.layer.shadowOffset = CGSizeMake(0.0, 0.0);
add_member.layer.shadowOpacity = 0.0;
[add_member setTitle:#"Add Member" forState:UIControlStateNormal];
add_member.titleLabel.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:16];
[add_member addTarget:self action:#selector(AddNewMember:) forControlEvents:UIControlEventTouchUpInside];
[add_member setTitleColor:[UIColor colorWithRed:140.0/255.0 green:198.0/255.0 blue:63.0/255.0 alpha:1.0] forState:UIControlStateNormal];//set the color this is may be different for iOS 7
add_member.frame=CGRectMake(10, 5, 284, 30); //set some large width to ur title
[footerView addSubview:add_member];
return footerView;
}
#pragma mark - Add member
-(IBAction)AddNewMember:(id)sender
{
//Some code
}

Make the property for the button and the mention the property name inside action block like this.
-(IBAction)btn_check:(id)sender
{
BOOL buttonstate;//default state is false.
if(!buttonstate)
{
//Declare your action code here.
//Use the button property name here for your action.
}
else
{
//Declare the button release code here ,its not mandatory.
}

Related

Tableview scrolling Checked button image automatically hide

I am developing IOS App. Using tableview to expand and collpase. Add Button on TableviewCell for check or Uncheck. Example I am Selected First Row button. Than scrolling tableview and select last header to last row button selected. Than again scrolling and see first index selected button image hidden.
Code..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (self.sectionNames.count > 0) {
_tableView.backgroundView = nil;
return self.sectionNames.count;
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray *arrayOfItems = [self.sectionItems objectAtIndex:section];
return arrayOfItems.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (self.sectionNames.count) {
return [self.sectionNames objectAtIndex:section];
}
return #"";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; {
return 44.0;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
// recast your view as a UITableViewHeaderFooterView
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
// header.contentView.backgroundColor = [UIColor colorWithHexString:#"#484848"];
header.contentView.backgroundColor = [UIColor lightGrayColor];
header.textLabel.textColor = [UIColor whiteColor];
header.textLabel.font = [UIFont fontWithName:#"SourceSansPro SemiBold" size:15.0];
UIImageView *viewWithTag = [self.view viewWithTag:kHeaderSectionTag + section];
if (viewWithTag) {
[viewWithTag removeFromSuperview];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// for(UIView *subview in [cell subviews]) {
// [subview removeFromSuperview];
// }
UILabel *sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(35.0f, 12.0f, 120.0f, 20.f)];
sectionLabel.font = [UIFont systemFontOfSize:14.0f];
sectionLabel.textColor = [UIColor blackColor];
sectionLabel.lineBreakMode = NSLineBreakByWordWrapping;
sectionLabel.numberOfLines = 3;
[cell addSubview:sectionLabel];
NSArray *section = [self.sectionItems objectAtIndex:indexPath.section];
sectionLabel.text = [section objectAtIndex:indexPath.row];
UIButton *button = [[UIButton alloc]initWithFrame: CGRectMake(5.0f, 9.0f, 25.0f, 25.0f)];
button.layer.borderColor=[[UIColor colorWithRed:244.0f/255.0f
green:129.0f/255.0f
blue:32.0f/255.0f
alpha:1.0] CGColor];
[button.layer setBorderWidth: 1.0];
button.tag = indexPath.section;
NSString *data = [section objectAtIndex:indexPath.row]; //For Selected Fliters
for (int i=0; i<[filterArray count]; i++) {
NSDictionary *dict = [filterArray objectAtIndex:i];
NSString *fliterTickValue = [dict valueForKey:#"filterValue"];
if ([fliterTickValue isEqualToString:data]) {
UIImage *img = [UIImage imageNamed:#"tick.png"];
[button setImage: img forState:UIControlStateNormal];
}else{
UIImage *img = [UIImage imageNamed:#""];
[button setImage: img forState:UIControlStateNormal];
}
}
[button addTarget:self action:#selector(fliterFields:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:button];
return cell;
}
Imho, your calls [cell addSubview:] is not correct. In case that cell is re-used, it will already have those subviews and resulting layout of your cell is not quite clear.
I suggest you to design your cell in xib and load it when needed. Then your cellForRowAtIndexPath becomes simpler and deals mostly with data populating. Subviews you don't need at the moment can be hidden and so on. If you need code and design example - let me know.

How to change button background color which is added on table view cell when we tapped on it?

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.

How can i round corners of container table view?

I have a main view controller. It contains a table view controller ( in a container ) , i want to round out the tableview so it shows similarly to the facebook login one.
Code i have used in the child view controller ( which is a tableview controller ) in viewDidLoad :
self.tableView.layer.cornerRadius = 10.0f;
self.tableView.layer.masksToBounds = YES;
self.tableView.clipsToBounds = YES;
self.tableView.backgroundColor = [UIColor clearColor];
Result :
As you can see , when the field is selected , the corners SEEM rounded , but the white space remains. How can i make them rounded even when it isn't selected ?
Using : XCODE 5 , IOS 7
As you requested me to do, here is the code you wanted:
for (CALayer *subLayer in self.tableView.layer.sublayers)
{
subLayer.cornerRadius = 10;
subLayer.masksToBounds = YES;
}
Try this
#interface CustomtableViewController : UITableViewController<UITableViewDelegate, UITableViewDataSource>
{
UITextField * username;
UIButton * submit;
}
#implementation CustomtableViewController
- (void)viewDidLoad
{
UIView *newView = [[UIView alloc]initWithFrame:CGRectMake(10, 70, 300, 45)];
submit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[submit setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[submit setTitleColor:[UIColor colorWithWhite:0.0 alpha:0.56] forState:UIControlStateDisabled];
[submit setTitle:#"Login" forState:UIControlStateNormal];
[submit.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
[submit setFrame:CGRectMake(10.0, 15.0, 280.0, 44.0)];
[newView addSubview:submit];
[self.tableView setTableFooterView:newView];
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//self.tableView.contentOffset = CGPointMake( 10, 320);
[self.tableView setContentInset:UIEdgeInsetsMake(50,0,0,0)];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([indexPath section] == 0) {
username = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
username.adjustsFontSizeToFitWidth = YES;
username.textColor = [UIColor blackColor];
if ([indexPath row] == 0) {
username.placeholder = #"example#gmail.com";
username.keyboardType = UIKeyboardTypeEmailAddress;
username.returnKeyType = UIReturnKeyNext;
cell.textLabel.text = #"Username";
username.clearButtonMode = YES;
}
else {
username.placeholder = #"minimum 6 characters";
username.keyboardType = UIKeyboardTypeDefault;
username.returnKeyType = UIReturnKeyDone;
username.secureTextEntry = YES;
cell.textLabel.text = #"Password";
username.clearButtonMode = UITextFieldViewModeAlways;
}
username.backgroundColor = [UIColor whiteColor];
username.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
username.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
username.textAlignment = NSTextAlignmentLeft;
username.tag = 0;
username.clearButtonMode = UITextFieldViewModeAlways; // no clear 'x' button to the right
[username setEnabled: YES];
[cell.contentView addSubview: username];
}
// Configure the cell...
return cell;
}
Here, i've created just two textfields for username and password. You can use the else if condition to insert any no of textfields in each of the successive rows according to your needs.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [NSString stringWithFormat:#"User Login"];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 50;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
return #"";
}
So, my code here is just used for creating a login page with two textfields(Username and Password) and a Login button. You can modify my code according to your needs. Cheers!

Add tableview cell with the value of UITextfield

I have a UITextField in a UITableView header. When the user enters anything in the UITextFields, the entry gets added to a NSMutableArray.
I want to create a new UITableCell with the value of the UITextField entry whenever textFieldShouldReturn is called.
I tried using reloadData but that seems to empty my array completely.
Any suggestions? Thanks
- (BOOL)textFieldShouldReturn:(UITextField *)task
{
[task resignFirstResponder];
[self.tasksArray addObject:task.text];
NSLog(#"Test %#", self.tasksArray);
}
My cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
SwipeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[SwipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
[cell setDelegate:self];
[cell.contentView setBackgroundColor:[UIColor whiteColor]];
// Setting the default inactive state color to the tableView background color
[cell setDefaultColor:self.tableView.backgroundView.backgroundColor];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
[cell.textLabel setText:self.task.text];
self.view = tableView;
cell.mode = SwipeTableViewCellModeExit;
return cell;
}
My UITableView header :
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{
float width = tableView.bounds.size.width;
int fontSize = 18;
int padding = 1;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0,width, fontSize+11)];
view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
view.userInteractionEnabled = YES;
view.tag = section;
UITextField *task = [[UITextField alloc] initWithFrame:CGRectMake(padding, 2,
width - padding , fontSize + 11)];
task.text = #"Type here";
task.borderStyle = UITextBorderStyleRoundedRect;
task.textAlignment = NSTextAlignmentCenter;
task.backgroundColor = [UIColor whiteColor];
task.textColor = [UIColor blackColor];
task.delegate = self;
task.font = [UIFont boldSystemFontOfSize:fontSize];
[view addSubview:task];
self.tasksArray = [[NSMutableArray alloc] init];
return view;
}
viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
self.tasksArray = [NSMutableArray arrayWithCapacity:0];
self.title = #"Test";
self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[backgroundView setBackgroundColor:[UIColor colorWithRed:227.0 / 255.0
green:227.0 / 255.0
blue:227.0 / 255.0
alpha:1.0]];
[self.tableView setBackgroundView:backgroundView];
}
Remove [cell.textLabel setText:self.task.text];
And then,
Insert [self.yourTableOutletName reloadData]; after [self.tasksArray addObject:task.text];
Now your code will reload the tableView after adding a object into self.taskArray.
And then,
To reflect your array in tablView use this line.
Insert [cell.textLabel setText:[self.tasksArray objectAtIndex:indexPath.row]]; after [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
This line pulls the data incorrectly: [cell.textLabel setText:self.task.text];
self.view = tableView;
It should be from your array.
Also you never reload data, that should be the last line in textFieldShouldReturn

strike on the uilabel disappears in uitableview did select cell

1)i want to create a striked text so i have used thet ext frame and i have created it and keep on the lbal it works fine when i have used it in the table cell when i am selecting the cell the strike on the label disaperared
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#pragma mark TableView delegate method.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView1
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView1 numberOfRowsInSection:(NSInteger)section
{
return 4;
}
- (CGFloat)tableView:(UITableView *)tableView1 heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
tableView1.backgroundColor = [UIColor clearColor];
cell=nil;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
// cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"strip_11C.png"]];
//cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"strip_11C_h.png"]];
UILabel *price1_lbl = [[UILabel alloc] initWithFrame:CGRectMake(2,80,100,26)];
price1_lbl.text = #"label";
price1_lbl.textColor = [UIColor grayColor];
price1_lbl.font = [UIFont fontWithName:#"Arial-BoldMT" size:(13.0)];
price1_lbl.backgroundColor = [UIColor clearColor];
NSString *string =price1_lbl.text;
CGSize stringSize = [string sizeWithFont:price1_lbl.font];
CGRect buttonFrame = price1_lbl.frame;
CGRect labelFrame = CGRectMake(buttonFrame.origin.x ,
4+buttonFrame.origin.y + stringSize.height/2,
stringSize.width, 1);
UILabel *lineLabel = [[UILabel alloc] initWithFrame:labelFrame];
lineLabel.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:price1_lbl];
[cell.contentView addSubview:lineLabel];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
secondviewcontroller *obj=[[secondviewcontroller alloc]initWithNibName:#"secondviewcontroller" bundle:nil];
[self.navigationController pushViewController:obj animated:YES];
}
Try to add the strikethrough line directly to the label with the text (price1_lbl). If that doesn't work you may want to give this lib a try.
UPDATE:
You can use this code:
CGSize size = [price1_lbl.text sizeWithFont:[UIFont systemFontOfSize:16.0f]];
UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0 , label.frame.size.height / 2, size.width, 1)];
line.backgroundColor = [UIColor blackColor];
[price1_lbl addSubview:line];

Resources