UITextFiled don't show clearButton sometimes - ios

I add a simple UITableView to my project,and every cell include a UITextField with clearButtonMode = UITextFieldViewModeAlways.
but strange issue occurs .when I reloadData,some textfield don't show clear button.
so I grab the part and build a sample and never find this issue.
I just wonder is some property has a effect to the textField.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"userIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
for (UIView *sv in cell.contentView.subviews) {
[sv removeFromSuperview];
}
UITextField *tf = [[UITextField alloc] initWithFrame:cell.bounds];
tf.text = [self.tb_data[indexPath.row];
tf.rightViewMode = UITextFieldViewModeAlways;
tf.clearButtonMode = UITextFieldViewModeAlways;
tf.tag = indexPath.row+100;
tf.delegate = self;
[[cell contentView] addSubview:tf];
return cell;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField.tag >= 100) {
return NO;
}
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
if (textField.tag >= 100) {
[self.tb_data removeObjectAtIndex:textField.tag-100];
[self.tb beginUpdates];
[self.tb deleteRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:textField.tag-100 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
[UIView animateWithDuration:0.3
animations:^{
CGRect frame = self.tb.frame;
frame.size.height = 40*self.tb_data.count;
self.tb.frame = frame;
}];
[self.tb endUpdates];
[self.tb reloadData];
}
return YES;
}

Related

view duplicated on different cells after cell is selected

I have a tableviewcontroller and a custom cell. What i wanna do is when i tap the cell, the cell is supposed to exapand and a view (graph view actually) is supposed to become subviewed inside the cell. Now the problem is that everything works fine but the graph is duplicated on some other cells as well.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ProductsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (cell == nil)
{
NSLog(#"empty cell");
}
//Product Label
cell.productNameLabel.text = #"something";
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
indexPathforChart = indexPath;
[self performSelector:#selector(addChart:) withObject:indexPath afterDelay:0.2];
[tableView beginUpdates];
[tableView endUpdates];
[tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
}
-(void)addChart:(NSIndexPath*)indexPath
{
BEMSimpleLineGraphView *myGraph = [[BEMSimpleLineGraphView alloc] initWithFrame:CGRectMake(0, 60, screenSize.width, 200)];
myGraph.dataSource = self;
myGraph.delegate = self;
myGraph.interpolateNullValues = YES;
myGraph.enableTouchReport = YES;
myGraph.tag = 100;
myGraph.animationGraphStyle = BEMLineAnimationDraw;
myGraph.enablePopUpReport = YES;
myGraph.enableXAxisLabel = YES;
myGraph.colorXaxisLabel = [UIColor darkGrayColor];
ProductsTableViewCell *cell = (ProductsTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.contentView addSubview:myGraph];
[cell setNeedsLayout];
[cell setNeedsDisplay];
myGraph.colorTop = [UIColor clearColor];
myGraph.colorBottom = [UIColor clearColor];
myGraph.colorLine = [UIColor darkGrayColor];
myGraph.colorPoint = [UIColor lightGrayColor];
}
This is caused by cell re-use.
ProductsTableViewCell *cell = (ProductsTableViewCell*)[self.tableView
cellForRowAtIndexPath:indexPath];
[cell.contentView addSubview:myGraph];
You added myGraph as a subview in the cell without removing it when the cell is re-used by some other index path while you scroll the table view.
The most appropriate way should be having a custom view inside the cell for drawing your graph, instead of adding/removing the graph view when needed. For the sake of scrolling performance, you may also cache the graph in case it will be used when user scrolls back and forth.
Cells are reused, so before loading a new cell you should implement the method prepareForReuse and add/remove or hidden/unhidden the views your cell requires.
So basically, ProductsTableViewCell should implement the method prepareForReuse. The easiest way to remove your BEMSimpleLineGraphView based on your code would be:
- (void) prepareForReuse{
UIView *v = [cell.contentView viewWithTag:100];
if ( v ) {
[v removeFromSuperView];
}
}
However, I don't consider using viewWithTag is the best solution so I would change the code into something similar to:
tableviewcontroller
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ProductsTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[tableView beginUpdates];
[cell addChart];
[tableView endUpdates];
[tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
}
ProductsTableViewCell
#interface DLSContactUsViewController ()
#property (strong,nonatomic) BEMSimpleLineGraphView *myGraph;
#end
-(void)addChart
{
if ( ![self.myGraph isDescendantOfView] ){
[self.contentView addSubview:self.myGraph];
[self setNeedsLayout];
[self setNeedsDisplay];
}
}
- (BEMSimpleLineGraphView*) myGraph{
if ( !_myGraph ) {
_myGraph = [[BEMSimpleLineGraphView alloc] initWithFrame:CGRectMake(0, 60, screenSize.width, 200)];
_myGraph.dataSource = self;
_myGraph.delegate = self;
_myGraph.interpolateNullValues = YES;
_myGraph.enableTouchReport = YES;
_myGraph.tag = 100;
_myGraph.animationGraphStyle = BEMLineAnimationDraw;
_myGraph.enablePopUpReport = YES;
_myGraph.enableXAxisLabel = YES;
_myGraph.colorXaxisLabel = [UIColor darkGrayColor];
_myGraph.colorTop = [UIColor clearColor];
_myGraph.colorBottom = [UIColor clearColor];
_myGraph.colorLine = [UIColor darkGrayColor];
_myGraph.colorPoint = [UIColor lightGrayColor];
}
return _myGraph;
}
- (void) prepareForReuse{
if ( [self.myGraph isDescendantOfView] && !self.isSelected ) {
[myGraph removeFromSuperView];
}
}

UITableViewCell wrong height if is present only one item

I have a UITableView with a custom cell and at the beginning all is empty.
My UITableViewCell has a UITextView and when i tap on the screen i create a new cell and fire on it:
#import "MemoViewController.h"
#import "MemoViewCell.h"
#import "MemoModel.h"
static NSString *CellIdentifier = #"MemoCell";
#interface MemoViewController () <UITextViewDelegate>
#property (nonatomic, strong) MemoModel *model;
#property (nonatomic, strong) NSMutableDictionary *offscreenCells;
#end
#implementation MemoViewController
{
NSIndexPath *currentIndexPath;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.model = [[MemoModel alloc] init];
//[self.model populateDataSource];
self.offscreenCells = [NSMutableDictionary dictionary];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[MemoViewCell class] forCellReuseIdentifier:CellIdentifier];
self.tableView.rowHeight = UITableViewAutomaticDimension;
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(insertNewRow:)];
gestureRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:gestureRecognizer];
currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]
initWithTitle:#"Modifica"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(editButtonPressed:)];
self.navigationItem.rightBarButtonItem = editButton;
}
-(IBAction)editButtonPressed:(UIBarButtonItem *)sender
{
if ([sender.title isEqualToString:#"Fine"]) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.model.dataSource count] - 1 inSection:0];
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.bodyLabel resignFirstResponder];
}
}
-(void)insertNewRow:(UIGestureRecognizer *)gestureRecognizer
{
CGPoint point = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
if (indexPath == nil) {
[self.model addObject];
[self.tableView reloadData];
indexPath = [NSIndexPath indexPathForRow:[self.model rowsCount] - 1 inSection:0];
}
[self.navigationItem.rightBarButtonItem setTitle:#"Fine"];
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.bodyLabel becomeFirstResponder];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contentSizeCategoryChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)contentSizeCategoryChanged:(NSNotification *)notification
{
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.model.dataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ([self.model.dataSource count] > 0) {
NSDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:indexPath.row];
cell.bodyLabel.text = [dataSourceItem valueForKey:#"body"];
}
cell.bodyLabel.delegate = self;
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reuserIdentifier = CellIdentifier;
if ([self.model.dataSource count] > 0) {
MemoViewCell *cell = [self.offscreenCells objectForKey:reuserIdentifier];
if (!cell) {
cell = [[MemoViewCell alloc] init];
[self.offscreenCells setObject:cell forKeyedSubscript:reuserIdentifier];
}
[cell updateFonts];
NSDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:indexPath.row];
cell.bodyLabel.text = [dataSourceItem valueForKey:#"body"];
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1;
CGFloat toReturn = height + [self measureHeightOfUITextView:cell.bodyLabel] - 30;
NSLog(#"Height for Row %li is %f", (long)indexPath.row, toReturn);
return toReturn;
} else {
return 44.0;
}
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44.0;
}
/*
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MemoViewCell *cell = (MemoViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.bodyLabel.userInteractionEnabled = YES;
[cell.bodyLabel becomeFirstResponder];
}
*/
#pragma mark - Text View Delegate
- (void)textViewDidBeginEditing:(UITextView*)textView
{
MemoViewCell* cell = (MemoViewCell *)[self parentCellFor:textView];
if (cell)
{
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
currentIndexPath = indexPath;
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
}
/*
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:currentIndexPath];
[cell.bodyLabel becomeFirstResponder];
[self.tableView selectRowAtIndexPath:currentIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
return YES;
}
*/
- (UITableViewCell*)parentCellFor:(UIView*)view
{
if (!view)
return nil;
if ([view isMemberOfClass:[MemoViewCell class]])
return (UITableViewCell*)view;
return [self parentCellFor:view.superview];
}
-(void)textViewDidChange:(UITextView *)textView
{
NSMutableDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:currentIndexPath.row];
[dataSourceItem setObject:textView.text forKey:#"body"];
[self.model.dataSource replaceObjectAtIndex:currentIndexPath.row withObject:dataSourceItem];
if ([textView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height != textView.frame.size.height) {
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return YES;
}
- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
if ([textView respondsToSelector:#selector(snapshotViewAfterScreenUpdates:)])
{
CGRect frame = textView.bounds;
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:#"\n"])
{
textToMeasure = [NSString stringWithFormat:#"%#-", textView.text];
}
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = #{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
#end
With this code (insertNewRow:) i first create a new object on dataModel, i reload the data to setup all the table and next i make the first responder my last added UITextView.
On textViewDidChange: delegate i update the table to expand the row(s) to the UITextViewContent.
All works fine if i have at least 2 rows. If i have only one row, all rows assume all the same width.
If your cell's height is fixed then just use this method with return.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
but if your cell's height is dynamic then you need to do some calculation and then return the correct height for the cell.

iPhone SDK: App crash on textField resignFirstResponder

I an creating app that needs expand tableview feature like below screen. when i click the row the textbox and button will appear.when i click on textbox and press return from keyboard, application crashed.
When I tried to resign the text box showing in screenshot, application crashed,
I write Following Code...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"AffiliationCell"];
cell.backgroundColor = [UIColor clearColor];
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 130, 44)];
lblTitle.tag = indexPath.row+1;
lblTitle.font = [UIFont fontWithName:Oxygen_Regular size:13];
lblTitle.text = [NSString stringWithFormat:#"Affiliation %d",indexPath.row+1];
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor blackColor];
[cell.contentView addSubview:lblTitle];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* checkCell = [tableView cellForRowAtIndexPath:indexPath];
[tableView beginUpdates];
if ([indexPath compare:self.checkedIndexPath] == NSOrderedSame) {
self.checkedIndexPath = nil;
[viewScreenName removeFromSuperview];
} else {
//add view
[txtScreenName setClearsOnInsertion:YES];
viewScreenName.frame = CGRectMake(0, 45, viewScreenName.frame.size.width, viewScreenName.frame.size.height);
[checkCell.contentView addSubview:viewScreenName];
self.checkedIndexPath = indexPath;
}
[tableView endUpdates];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if ([indexPath compare:self.checkedIndexPath] == NSOrderedSame) {
return expandedCellHeight; // Expanded height
}
return 44 ;
}
#pragma mark - TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
tblAffiliations.frame = updatedFrame;
return TRUE;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
#try {
if (textField) {
[textField resignFirstResponder];
}
}
#catch (NSException *exception) {
NSLog(#"Exception %#",exception);
}
tblAffiliations.frame = currentFrame;
return TRUE;
}
Please Help.
It seems that you are using a textfield that is being deallocated. I think the best way to proceed is adding the textfield in each cell like you added your label and setting it to be hidden. On the didSelectRow delegate, you should set the label as hidden and the textfield not hidden. It is better to work with hidden flag that to remove and add from superview.
Wish it helps.

UITableView with multiple sections and accessoryType

This is my functions for my table View.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.categories count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return #"test";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d", self.collections.count);
return [self.collections count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
switch ([indexPath section])
{
case 0:
self.myList = self.collections;
break;
}
cell.textLabel.text = self.collections[indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 48;
}
Actually, with this code, my table view show all the section and cells in the same view.
However, I would like a table view which show, at first time, a row with my title of section.
When i click on the row where there is my title of section, i would like to show the cells which are in the section. How can i do that?
Do i need 2 tableViews?
You should have to take two uitableview in that delegate will be same after that you should have to use this code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"%#",indexPath];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==Nil)
{
cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
if (isDeptSelected)
{
//[cell.imageView setImage:[UIImage imageNamed:#"Department.png"]];
cell.textLabel.text = [[arrDept_Detail valueForKey:#"dep_Name"]objectAtIndex:indexPath.row];
}
else if (isEmpSelected)
{
[cell.imageView setImage:[UIImage imageNamed:#"Emp_Images"]];
cell.textLabel.text = [[arrEmp_Detail valueForKey:#"emp_Name"]objectAtIndex:indexPath.row];
}
// cell.textLabel.text=[[arrDept_Detail objectAtIndex:indexPath.row]valueForKeyPath:#"dep_Name"];
[cell setBackgroundColor:[UIColor brownColor]];
[cell.textLabel setTextColor:[UIColor greenColor]];
[cell.textLabel setFont:[UIFont fontWithName:#"Georgia-Bold" size:16]];
cell.textLabel.highlightedTextColor=[UIColor purpleColor];
[self.view setBackgroundColor:[UIColor brownColor]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (isDeptSelected)
{
isDeptSelected=false;
isEmpSelected=true;
[btnDoneclick setHidden:NO];
[self.view addSubview:btnDoneclick];
EmpInDepTableView=[[UITableView alloc]initWithFrame:CGRectMake(160, 284,0, 0)];
[EmpInDepTableView setDelegate:self];
[EmpInDepTableView setDataSource:self];
[EmpInDepTableView setHidden:NO];
[EmpInDepTableView setBackgroundColor:[UIColor brownColor]];
EmpInDepTableView.layer.borderWidth=3.0f;
EmpInDepTableView.layer.cornerRadius=10.0f;
[self.view addSubview:EmpInDepTableView];
self.tabBarController.tabBar.userInteractionEnabled=NO;
UITableViewCell *cell=[Dept_TableView cellForRowAtIndexPath:indexPath];
DeptId=[Dep_Detail fetchDeptId_DeptName:cell.textLabel.text];
arrEmp_Detail = [[Emp_Detail fetchEmp_By_DeptId:DeptId]mutableCopy];
[UITableView animateWithDuration:0.6 animations:^
{
[EmpInDepTableView setFrame:CGRectMake(0, 64,320, 430)];
[btnDoneclick setFrame:CGRectMake(0,490,320,29)];
}completion:^(BOOL finished)
{
[EmpInDepTableView reloadData];
}];
}
else if (isEmpSelected)
{
}
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] init];
[view setBackgroundColor:[UIColor brownColor]];
return view;
}
-(IBAction)btnDoneclicked:(id)sender
{
[EmpInDepTableView reloadData];
isDeptSelected=true;
isEmpSelected=false;
[btnDoneclick setHidden:YES];
self.tabBarController.tabBar.userInteractionEnabled=YES;
[UITableView animateWithDuration:0.6 animations:^
{
[EmpInDepTableView setFrame:CGRectMake(160, 284, 0, 0)];
[btnDoneclick setFrame:CGRectMake(160, 284, 0, 0)];
[self.view setBackgroundColor:[UIColor brownColor]];
}completion:^(BOOL finished)
{
}];
}

Seeing a TextField as a subview of a UICell

I have added a TextField to a UICell in order to allow a user to change the TextLabel of said cell. Everything works fine in that the keyboard appears and the TextLabel changes to the correct value when I press return. I can't, however, SEE the text as it is being edited. Here is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *aCategory = aCell.textLabel.text;
[[aCell detailTextLabel] setText:aCategory];
[aCell setEditing:YES animated:YES];
UITextField *userText =[[UITextField alloc] init];
userText.tag = indexPath.row;
[aCell addSubview:userText];
NSArray *test =[aCell subviews];
NSLog(#"I have %d many subviews",[test count]);
userText.alpha=1.0;
[userText setDelegate:self];
userText.autocorrectionType = UITextAutocorrectionTypeNo;
[aCell bringSubviewToFront:userText];
[userText becomeFirstResponder];
}
I would like to do it without custom cells if possible. Thanks in advance.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *aCategory = aCell.textLabel.text;
[[aCell detailTextLabel] setText:aCategory];
UITextField *userText = [[UITextField alloc] initWithFrame:aCell.textLabel.frame];
userText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
userText.font = aCell.textLabel.font;
userText.text = aCell.textLabel.text;
aCell.textLabel.text = nil;
userText.tag = indexPath.row;
[aCell addSubview:userText];
[userText setDelegate:self];
userText.autocorrectionType = UITextAutocorrectionTypeNo;
[aCell bringSubviewToFront:userText];
[userText becomeFirstResponder];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];
UITableViewCell *aCell = [self.tableView cellForRowAtIndexPath:indexPath];
aCell.textLabel.text = textField.text;
[textField removeFromSuperview];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

Resources