I've got 3 table cells and somehow it displays the two last contents in the last cell. I did something wrong somewhere in my code, but I don't know where since I just follow a tutorial and try to do the same like in the tutorial, but instead of 2 cells I want 3 editable cells.
the full code:
#import "LocationAddViewController.h"
#import "Location.h"
#interface LocationAddViewController ()
- (void)prepareCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath;
- (UIBarButtonItem *)newCancelButton;
- (UIBarButtonItem *)newSaveButton;
- (UITextField *)newTextField;
#end
#implementation LocationAddViewController
#synthesize location;
#synthesize titleField;
#synthesize authorField;
#synthesize atextField;
#synthesize delegate;
- (void)dealloc {
[location release];
[titleField release];
[authorField release];
[atextField release];
[super dealloc];
}
- (id)initWithLocation:(Location *)aLocation andDelegate:(id)aDelegate {
if (self = [super initWithStyle:UITableViewStyleGrouped]) {
self.location = aLocation;
self.delegate = aDelegate;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.allowsSelection = NO;
titleField = [self newTextField];
titleField.keyboardType = UIKeyboardTypeASCIICapable;
[titleField becomeFirstResponder];
authorField = [self newTextField];
authorField.keyboardType = UIKeyboardTypeASCIICapable;
atextField = [self newTextField];
atextField.keyboardType = UIKeyboardTypeASCIICapable;
if (location.onelocationId) {
titleField.text = location.title;
authorField.text = location.author;
atextField.text = location.text;
} else {
titleField.placeholder = #"Title";
authorField.placeholder = #"Author";
atextField.placeholder = #"Text";
}
UIBarButtonItem *cancelButton = [self newCancelButton];
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
UIBarButtonItem *saveButton = [self newSaveButton];
self.navigationItem.rightBarButtonItem = saveButton;
saveButton.enabled = NO;
[saveButton release];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (location.onelocationId) {
self.title = #"Edit Location";
} else {
self.title = #"Add Location";
}
}
-(IBAction)cancel {
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)save {
location.title = titleField.text;
location.author = authorField.text;
location.text = atextField.text;
[self.delegate didChangeLocation:location];
[self.navigationController popViewControllerAnimated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =
[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil] autorelease];
[self prepareCell:cell forIndexPath:indexPath];
return cell;
}
- (void)prepareCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
[cell.contentView addSubview:titleField];
} else {
[cell.contentView addSubview:authorField];
[cell.contentView addSubview:atextField];
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
if (textField == titleField) {
[authorField becomeFirstResponder];
}
if (titleField == authorField) {
[self save];
}
return YES;
}
- (IBAction)textFieldChanged:(id)sender {
BOOL enableSaveButton =
([self.titleField.text length] > 0) && ([self.authorField.text length] > 0) && ([self.atextField.text length] > 0);
[self.navigationItem.rightBarButtonItem setEnabled:enableSaveButton];
}
- (UIBarButtonItem *)newCancelButton {
return [[UIBarButtonItem alloc]
initWithTitle:#"Cancel"
//auch im Original gelb
style:UIBarButtonSystemItemCancel
target:self
action:#selector(cancel)];
}
- (UIBarButtonItem *)newSaveButton {
return [[UIBarButtonItem alloc]
initWithTitle:#"Save"
//auch im Original gelb
style:UIBarButtonSystemItemSave
target:self
action:#selector(save)];
}
- (UITextField *)newTextField {
UITextField *textField =
[[UITextField alloc] initWithFrame:CGRectMake(10, 10, 285, 25)];
textField.font = [UIFont systemFontOfSize:16];
textField.delegate = self;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
[textField addTarget:self
action:#selector(textFieldChanged:)
forControlEvents:UIControlEventEditingChanged];
return textField;
}
#end
I suppose the problem is here:
- (void)prepareCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
[cell.contentView addSubview:titleField];
} else {
[cell.contentView addSubview:authorField];
[cell.contentView addSubview:atextField];
}
}
I'm not too much into the whole programming, but I guess I have to write 3 if-clauses? (Something like if (...) elsif (...) else (...)) Does anybody know it better than me?
In your prepareCell:forIndexPath, you are adding both subviews into the last cell. You can use an elseif just as your described so your method looks something like this
if (indexPath.row == 0) {
[cell.contentView addSubview:titleField];
} else if (indexPath.row == 1) {
[cell.contentView addSubview:authorField];
} else {
[cell.contentView addSubview:atextField];
}
You can add any amount of else ifs after the if.
You're right about the source of the error. You're adding authorField & atextField at the same coordinates. The correct way to include 3 causes for ifs is:
if (/* condition 1 */) {
}
else if ( /* condition 2 */) {
}
else if ( /* condition 3 */) {
}
Do this:
- (void)prepareCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
[cell.contentView addSubview:titleField];
} else if(indexPath.row == 1) {
[cell.contentView addSubview:authorField];
}else if(indexPath.row == 2) {
[cell.contentView addSubview:atextField];
}
}
if (indexPath.row == 0) {
[cell.contentView addSubview:titleField];
} else if(indexPath.row == 1) {
[cell.contentView addSubview:authorField];
}else if(indexPath.row == 2) {
[cell.contentView addSubview:atextField];
}
Related
I've been following a tutorial teaching how to make a tableview with a search bar. I got this to work without problems, but now I learned to make the same tableview but instead of local arrays, I've been getting my data from parse as PFObjects.
I then tried to take the search bar and implant it in my new tableview which uses parse. I can't get this to work. Following the tutorial with the search bar they are using simple arrays stored locally..
Can anyone point me in the right direction of how to use a search bar in a tableview that gets its data from a parse database?
This is my code that works with my tableview that does NOT use parse.
#implementation RecipeBookViewController {
NSArray *recipes;
NSArray *searchResults;
}
#synthesize tableView = _tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
recipes = [NSArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto",
#"Full Breakfast", #"Hamburger", #"Ham and Egg Sandwich", #"Creme Brelee",
nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [recipes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath
- *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
[self performSegueWithIdentifier: #"showRecipeDetail" sender: self];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showRecipeDetail"]) {
RecipeDetailViewController *destViewController =
segue.destinationViewController;
NSIndexPath *indexPath = nil;
if ([self.searchDisplayController isActive]) {
indexPath = [self.searchDisplayController.searchResultsTableView
indexPathForSelectedRow];
destViewController.recipeName = [searchResults
objectAtIndex:indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
}
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:
(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar
scopeButtonTitles]
objectAtIndex:
[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
And this is my tableview which get its data from my parse database:
#implementation RecipeBookViewController {
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
// Custom the table
// The className to query on
self.parseClassName = #"Recipe";
// The key of the PFObject to display in the label of the default cell
style
self.textKey = #"name";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = NO;
// The number of objects to show per page
//self.objectsPerPage = 10;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(refreshTable:)
name:#"refreshTable"
object:nil];
}
- (void)refreshTable:(NSNotification *) notification
{
// Reload the recipes
[self loadObjects];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"refreshTable"
object:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (PFQuery *)queryForTable
{
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
// If no objects are loaded in memory, we look to the cache first
to fill the table
// and then subsequently do a query against the network.
/* if ([self.objects count] == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}*/
// [query orderByAscending:#"name"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:
(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell
PFFile *thumbnail = [object objectForKey:#"imageFile"];
PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
thumbnailImageView.image = [UIImage imageNamed:#"placeholder.jpg"];
thumbnailImageView.file = thumbnail;
[thumbnailImageView loadInBackground];
UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:#"name"];
UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
prepTimeLabel.text = [object objectForKey:#"prepTime"];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath*) indexPath
{
// Remove the row from data model
PFObject *object = [self.objects objectAtIndex:indexPath.row];
[object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self refreshTable:nil];
}];
}
- (void) objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];
NSLog(#"error: %#", [error localizedDescription]);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showRecipeDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
RecipeDetailViewController *destViewController =
segue.destinationViewController;
PFObject *object = [self.objects objectAtIndex:indexPath.row];
Recipe *recipe = [[Recipe alloc] init];
recipe.name = [object objectForKey:#"name"];
recipe.imageFile = [object objectForKey:#"imageFile"];
recipe.prepTime = [object objectForKey:#"prepTime"];
recipe.ingredients = [object objectForKey:#"ingredients"];
destViewController.recipe = recipe;
}
}
In my project I need to implement the UITableview with some of the tableView cells are expandable and some of them are independent. If it is expandable cell need to indicate the '+' symbol.enter image description here. Can any one please help me out
I have created a small demo,
https://github.com/haripalwagh/ExpandableTableviewCell
Screenshot 1 : Before expanding a cell
Screenshot 2 : After expanding a cell
#interface ViewController ()
<UITableViewDataSource,
UITableViewDelegate>
{
UITableView *tblView;
NSArray *cell0SubMenuItemsArray;
BOOL isSection0Cell0Expanded;
}
#end
#implementation ViewController
# pragma mark - View Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
tblView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
tblView.backgroundColor = [UIColor clearColor];
tblView.delegate = self;
tblView.dataSource = self;
tblView.allowsSelection = YES;
tblView.scrollEnabled = YES;
tblView.alwaysBounceVertical = YES;
[self.view addSubview:tblView];
cell0SubMenuItemsArray = #[#"First Static Menu Item", #"Second Static Menu Item", #"Third Static Menu Item"];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.view setNeedsLayout];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self updateViewDimensions];
}
- (void)updateViewDimensions
{
tblView.frame = CGRectMake(0, 40, 320, 550);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
# pragma mark - UITableView Delegate and Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
int cellCount = 2; // Default count - if not a single cell is expanded
if (isSection0Cell0Expanded)
{
cellCount += [cell0SubMenuItemsArray count];
}
return cellCount;
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCellId = #"CellId";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCellId];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.section == 0)
{
if (indexPath.row == 0)
{
cell.textLabel.text = #"Expandable Cell";
UIImageView *accessoryImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
if (isSection0Cell0Expanded) // Set accessory view according to cell state - EXPANDED / NOT EXPANDED
{
accessoryImageView.image = [UIImage imageNamed:#"Minus.png"];
cell.detailTextLabel.text = #"Status : Expanded";
}
else
{
accessoryImageView.image = [UIImage imageNamed:#"Plus.png"];
cell.detailTextLabel.text = #"Status : Not Expanded";
}
cell.accessoryView = accessoryImageView;
}
else
{
if (isSection0Cell0Expanded && [cell0SubMenuItemsArray count] >= indexPath.row) // Check Expanded status and do the necessary changes
{
cell.textLabel.text = [NSString stringWithFormat:#"%#", [cell0SubMenuItemsArray objectAtIndex:indexPath.row - 1]];
}
else
{
cell.textLabel.text = #"Static Cell";
}
}
}
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
{
// Change status of a cell reload table
isSection0Cell0Expanded = !isSection0Cell0Expanded;
[tblView reloadData];
}
}
You have to manage like this for every expandable cell.
Hope this will help you..
Try this control: https://github.com/jonasman/JNExpandableTableView
It supports what you say. Tapping on a cell expands it.
I would like to imitate the grouped table of the standard Contacts app (left). Each section has gray line dividers above and below. In my grouped table (right), there is no line above each section. And even stranger, the middle section has no lines at all.
#import "GroupViewController.h"
#import "UserCollectionViewCell.h"
#import "UIView+position.h"
#import "UIColor+style.h"
#import "UserPublicViewController.h"
#import "RecipientsGroupsModel.h"
static NSString* AVATAR_CELL_ID = #"groupUserCollectionUserView";
static const CGFloat AVATAR_ITEM_SPACING = 16.0;
static const CGFloat AVATAR_LINE_SPACING = 9.0;
static const CGFloat AVATAR_MARGIN = 15.5;
static const CGFloat AVATAR_CELL_WIDTH = 45.0;
static const CGFloat AVATAR_CELL_HEIGHT = 58.0;
typedef enum {
GroupViewControllerTableSectionTitle,
GroupViewControllerTableSectionUsers,
GroupViewControllerTableSectionDelete
} GroupViewControllerTableSection;
#interface GroupViewController ()
#property(nonatomic, strong) Group* group;
#property(nonatomic, strong) UICollectionView* avatarCollectionView;
#property(nonatomic, readonly) CGFloat usersHeight;
- (void)didLongTapAvatars:(UILongPressGestureRecognizer*)gesture;
#end
#implementation GroupViewController
#pragma mark UIViewController
- (NSString*)title
{
return #"Group";
}
- (void)loadView
{
[super loadView];
self.view.backgroundColor = [UIColor backgroundColor];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[self.tableView reloadData];
[self.avatarCollectionView reloadData];
}
#pragma mark GroupViewController ()
- (void)didLongTapAvatars:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan) {
[self setEditing:!self.isEditing animated:YES];
}
}
- (CGFloat)usersHeight
{
return ceilf(
self.group.users.count
/ floorf(
(
self.view.width
- 2 * AVATAR_MARGIN
+ AVATAR_ITEM_SPACING
)
/ (
AVATAR_ITEM_SPACING
+ AVATAR_CELL_WIDTH
)
)
)
* (AVATAR_CELL_HEIGHT + AVATAR_LINE_SPACING)
+ AVATAR_LINE_SPACING;
}
#pragma mark GroupViewController
- (instancetype)initWithGroup:(Group *)group
{
if (self = [super init]) {
self.group = group;
}
return self;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
case GroupViewControllerTableSectionTitle:
case GroupViewControllerTableSectionDelete:
return 44.0f;
break;
case GroupViewControllerTableSectionUsers:
return self.usersHeight;
break;
default:
return 0.0f;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 22.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
switch (section) {
case GroupViewControllerTableSectionDelete:
return 22.0f;
break;
default:
return 0.0f;
}
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// iOS 7 applies a transclucent view if you don't return your own view
return [[UIView alloc] init];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return [[UIView alloc] init];
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.isEditing) {
return GroupViewControllerTableSectionDelete + 1;
} else {
return GroupViewControllerTableSectionUsers + 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString* identifier = [NSNumber numberWithInteger:indexPath.section].stringValue;
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
switch (indexPath.section) {
case GroupViewControllerTableSectionTitle:
cell.textLabel.text = self.group.title;
break;
case GroupViewControllerTableSectionUsers: {
if (self.avatarCollectionView == nil) {
UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.sectionInset = UIEdgeInsetsMake(
AVATAR_LINE_SPACING,
AVATAR_MARGIN,
AVATAR_LINE_SPACING,
AVATAR_MARGIN
);
layout.itemSize = CGSizeMake(AVATAR_CELL_WIDTH, AVATAR_CELL_HEIGHT);
layout.minimumInteritemSpacing = AVATAR_ITEM_SPACING;
layout.minimumLineSpacing = AVATAR_LINE_SPACING;
self.avatarCollectionView = [[UICollectionView alloc]
initWithFrame:CGRectMake(
0.0,
0.0,
self.view.width,
self.usersHeight
)
collectionViewLayout:layout
];
self.avatarCollectionView.backgroundColor = [UIColor clearColor];
self.avatarCollectionView.dataSource = self;
self.avatarCollectionView.delegate = self;
[self.avatarCollectionView registerClass:[UserCollectionViewCell class] forCellWithReuseIdentifier:AVATAR_CELL_ID];
[self.avatarCollectionView addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(didLongTapAvatars:)]];
}
[cell.contentView addSubview:self.avatarCollectionView];
break;
}
case GroupViewControllerTableSectionDelete:
cell.textLabel.text = #"Delete Group";
cell.textLabel.textColor = [UIColor redColor];
break;
}
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return NO;
}
#pragma mark UICollectionViewDataSource
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UserCollectionViewCell* cell;
cell = [self.avatarCollectionView dequeueReusableCellWithReuseIdentifier:AVATAR_CELL_ID forIndexPath:indexPath];
cell.user = [self.group.users objectAtIndex:indexPath.row];
cell.isEditing = self.isEditing;
return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.group.users.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
User* user = [self.group.users objectAtIndex:indexPath.row];
if (self.isEditing) {
if (self.group.users.count <= 1) {
[RecipientsGroupsModel removeGroup:self.group];
[self.navigationController popViewControllerAnimated:YES];
} else {
[self.group.users removeObject:user];
[RecipientsGroupsModel updateGroup:self.group];
[self.avatarCollectionView deleteItemsAtIndexPaths:#[indexPath]];
}
} else {
[self.navigationController pushViewController:[[UserPublicViewController alloc] initWithUser:user] animated:YES];
}
}
#end
You can use the UITableViewDelegate methods:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
where you can specify any height you want for header and footer of any section. Return 0 in case you do not need a header or footer.
Then use the other two methods:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
Inside each of them, you can write the custom code to make them look as you want:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
view.backgroundColor = [UIColor grayColor];
// ...
// Other customizations, like adding the gray line, etc.
// ...
return view;
I'm Having a custom cell which is consist of 3 different textfield txtsq,txtPOB,txtRxunit , and this custom cell m taking in my table view Controller, in table view Controller class inside the tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath , now i want to set the 3 different range limit of my 3 different text field which is in custom cell but i fail to set range in my
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{
NSString *resultStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField.tag ==SQ) {
if([self isNumeric:resultStr]){
if(resultStr.length <= 3){
if(resultStr.length >= 1){
NSString *firstLetter = [resultStr substringWithRange:NSMakeRange(0, 1)];
if(![firstLetter isEqualToString:#"0"]){
return YES;
}
}
else{
return YES;
}
}
}
}else
if([self isNumeric:resultStr]){
if(resultStr.length <= 5){
if(resultStr.length >= 1){
NSString *firstLetter = [resultStr substringWithRange:NSMakeRange(0, 1)];
if(![firstLetter isEqualToString:#"0"]){
return YES;
}
}
else{
return YES;
}
}
}
return NO;
}
I have already defined cell.txtSQ.tag=SQ;
cell.txtPOB.tag =POB;
cell.txtRxUnit.tag=RXunit;
After using this code my table view data is not persistent.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (self.skuNameArray.count > 0) {
OrderCell *cell = nil;
cell = (OrderCell *)[tableView dequeueReusableCellWithIdentifier:#"OrderCell"];
if(cell == nil){
cell = (OrderCell *)[OrderCell cellFromNibNamed:#"OrderCell"];
}
// Set Tag
cell.tag = indexPath.row;
cell.txtSQ.tag = indexPath.row;
cell.txtPOB.tag = indexPath.row;
cell.txtRxUnit.tag = indexPath.row;
// cell.txtSQ.tag=SQ;
//set Delegate
cell.txtPOB.delegate = self;
cell.txtRxUnit.delegate = self;
cell.txtSQ.delegate = self;
//set Values
cell.lblSKU.text = self.skuNameArray[indexPath.row];
cell.txtSQ.text = self.sqArray[indexPath.row];
cell.txtPOB.text = self.pobArray[indexPath.row];
cell.txtRxUnit.text = self.rxUnitArray[indexPath.row];
if (self.index == PCP || self.index == CURRENT_DAY_REPORTING_DETAIL) {
cell.txtSQ.enabled = NO;
cell.txtRxUnit.enabled = NO;
cell.txtPOB.enabled = NO;
}
[cell.txtSQ addTarget:self action:#selector(sqChanged:) forControlEvents: UIControlEventEditingChanged];
[cell.txtPOB addTarget:self action:#selector(pobChanged:) forControlEvents: UIControlEventEditingChanged];
[cell.txtRxUnit addTarget:self action:#selector(rxUnitChanged:) forControlEvents: UIControlEventEditingChanged];
cell.backgroundColor = [UIColor clearColor];
return cell;
}
Your SQ may be dynamic . So, make it static.
or
you might not have set delegate to self. Do this :
cell.txtSQ.delegate = self;
cell.txtPOB.delegate = self;
cell.txtRxUnit.delegate = self;
Set your tag carefully :
// Set Tag
cell.txtSQ.tag = SQ;
cell.txtPOB.tag = POB;
cell.txtRxUnit.tag = RXunit;
I have a number of text fields that offer a selection of pre defined values in the form of a picker view. Occasionally, usually after a lot of text boxes have been filled in, the picker goes black, then the app crashes.
I cant seem to reproduce the problem, it just happens occasionally...reported by some users. As ive picked up this code form someone else maybe I have missed something?
Here is the code for the custom class for the text box/pickers
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.touchEnabled = YES;
self.textField = nil;
self.editableTextField = nil;
__selectedValue = #"";
self.pickerView = nil;
self.button = nil;
self.textValue = nil;
self.otherSelected = NO;
self.backgroundColor = [UIColor clearColor];
self.userInteractionEnabled = YES;
self.values = [NSArray arrayWithObjects:#"Value1", #"Value2", #"Other", nil];
}
return self;
}
- (void)layoutSubviews
{
if (self.textField == nil) {
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 31.0f)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.font = [UIFont systemFontOfSize:12.0f];
UIPickerView *pickerView = [[UIPickerView alloc] init];
[pickerView sizeToFit];
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator = YES;
if (self.textValue != nil && ![self.textValue isEqualToString:#""]) {
textField.text = self.textValue;
int matchedIndex = -1;
int otherIndex = -1;
for (int i = 0; i < self.values.count; i++) {
NSString *value = [self.values objectAtIndex:i];
if ([value isEqualToString:#"Other"]) {
otherIndex = i;
}
if ([self.textValue isEqualToString:[self.values objectAtIndex:i]]) {
matchedIndex = i;
}
}
if (matchedIndex > -1) {
[pickerView selectRow:matchedIndex inComponent:0 animated:NO];
} else if (otherIndex > -1) {
[pickerView selectRow:otherIndex inComponent:0 animated:NO];
}
}
textField.inputView = pickerView;
self.pickerView = pickerView;
UIToolbar *accessoryView = [[UIToolbar alloc] init];
[accessoryView sizeToFit];
accessoryView.barStyle = UIBarStyleBlackOpaque;
accessoryView.tintColor = [UIColor grayColor];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(pickerDone:)];
self.doneButton = doneButton;
accessoryView.items = [NSArray arrayWithObjects:spacer, doneButton, nil];
textField.inputAccessoryView = accessoryView;
[self addSubview:textField];
self.textField = textField;
}
if (self.button == nil) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor clearColor];
button.frame = self.bounds;
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.button = button;
}
}
- (void)buttonPressed:(id)sender
{
if (self.fieldDelegate != nil) {
[self.fieldDelegate performSelector:#selector(fieldBeganEditing:) withObject:self];
}
if (self.otherSelected) {
self.doneButton.action = #selector(textFieldDone:);
self.textField.inputView = nil;
} else {
self.doneButton.action = #selector(pickerDone:);
self.textField.inputView = self.pickerView;
}
[self.textField becomeFirstResponder];
}
- (void)textFieldDone:(id)sender
{
LogCmd();
[self.textField resignFirstResponder];
self.textField.inputView = self.pickerView;
self.doneButton.action = #selector(pickerDone:);
[self.textField becomeFirstResponder];
}
- (void)pickerDone:(id)sender
{
LogCmd();
NSString *value = [self.values objectAtIndex:[self.pickerView selectedRowInComponent:0]];
if (!self.otherSelected) {
self.textField.text = value;
__selectedValue = value;
}
[self.textField resignFirstResponder];
}
/*- (void)setValues:(NSArray *)values
{
_values = values;
[self.pickerView reloadAllComponents];
}*/
#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
LogCmd();
}
#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSString *value = [self.values objectAtIndex:row];
if ([value isEqualToString:#"Other"]) {
self.otherSelected = YES;
self.textField.text = #"";
__selectedValue = #"";
[self.doneButton setAction:#selector(textFieldDone:)];
self.textField.inputView = nil;
[self.textField resignFirstResponder];
[self.textField becomeFirstResponder];
//[self.textField performSelector:#selector(becomeFirstResponder) withObject:nil afterDelay:0.2];
} else {
self.otherSelected = NO;
self.textField.text = value;
__selectedValue = value;
}
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component
{
return [self.values objectAtIndex:row];
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.values.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}