I have a UITableView with 10 cells.Except the first cell, all are the same.
Around 3 cells are displayed on screen at a time. Each cell has a label which says "Claim". Depending on certain events, I change the "claim" in SOME cells to "claimed".
Problem is when I scroll the cells , the some other cells (whose "claim" I haven't changed to "claimed") also show as "claimed". This seems random and feel is due to cell reuse and poor implementation. Please review the code and help me approach this better.
My requirement is :
Display 10 cells out of which all are identical except the first one.
All identical cells have a button / label with text "claim"
When I press the button , "claim" should change to "Claimed" ONLY for that particular cell in which the button resides.
This change should persist event when I scroll.
Custom cell used is :
#import "CustomSaloonCell.h"
#implementation CustomSaloonCell
#synthesize claimButton;
#synthesize delegateListener;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.claimButton=[UIButton buttonWithType:UIButtonTypeSystem];
self.claimButton.frame=CGRectMake(30,140,80, 30);
[self.claimButton setTitle:#"claim" forState:UIControlStateNormal];
[self.claimButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
self.claimButton.titleLabel.font = [UIFont fontWithName:#"Arial" size:(22)];
[self.claimButton addTarget:self action:#selector(claimButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:self.claimButton];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)claimButtonPressed{
[self.delegateListener didClickedClaimButton:self];
}
#end
The cell creation function :
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row==0){
CustomHeaderCell *headerCell = [[CustomHeaderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"header_cell"];
headerCell.selectionStyle = UITableViewCellSelectionStyleNone;
return headerCell;
}
static NSString *cellIdentifier = #"HistoryCell";
// Similar to UITableViewCell, but
CustomSaloonCell *cell = (CustomSaloonCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[CustomSaloonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.claimButton.tag = indexPath.row+TAG_OFFSET;
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"salon.jpg"]];
cell.delegateListener = self;
return cell;
}
The delegate method which modifies the label is :
- (void) claimConfirmedDelegate:(NSInteger)tag{
CustomSaloonCell *selectedCell=(CustomSaloonCell*)[self.claimTableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:(tag-TAG_OFFSET)inSection:0]];
[selectedCell.claimButton setTitle:#"claimed" forState:UIControlStateNormal];
}
Save state of button (also title if your required) in separate instance mutable array.
When you pressed button and calling delegate method add that cell indexpath in your buttonStateArray.
Now check current indexPath in cellForRowAtIndexPath method: is containing buttonStateArray. If it present then change your button state and title yeah other thing if you want.
It will work after scrolling too.
Declare NSMutableArray *buttonStateArray; in .h file of tableview class.
Allocate it on initialization or after view loading.
- (void) claimConfirmedDelegate:(NSInteger)tag{
CustomSaloonCell *selectedCell=(CustomSaloonCell*)[self.claimTableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:(tag-TAG_OFFSET)inSection:0]];
[selectedCell.claimButton setTitle:#"claimed" forState:UIControlStateNormal];
[buttonStateArray addObject:[NSIndexPath indexPathForRow:(tag-TAG_OFFSET)inSection:0]];
}
Now in cellForRowAtIndexPath: method
for (NSIndexPath *selectedIndex in buttonStateArray){
if([selectedIndex isEqual:indexPath]){
//Change your state of button.
}
}
Related
I'm trying to get the indexPath.row of a button clicked inside a tableView row.
When the user clicks this button I get the index.row corresponding to the button very well, but when I add more objects to the source array to create more cells by calling reloadData, the rowButtonClicked in each cell it's no longer giving me the correct indexPath.row in example I press the index 20 and now the printed indexPath.row is 9.
In cellForRowAtIndexPath to add the event to the button:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
lBtnWithAction = [[UIButton alloc] initWithFrame:CGRectMake(liLight1Xcord + 23, 10, liLight1Width + 5, liLight1Height + 25)];
lBtnWithAction.tag = ROW_BUTTON_ACTION;
lBtnWithAction.titleLabel.font = luiFontCheckmark;
lBtnWithAction.tintColor = [UIColor blackColor];
lBtnWithAction.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[cell.contentView addSubview:lBtnWithAction];
}
else
{
lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
}
//Set the tag
lBtnWithAction.tag = indexPath.row;
//Add the click event to the button inside a row
[lBtnWithAction addTarget:self action:#selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
To do something with the clicked index:
-(void)rowButtonClicked:(UIButton*)sender
{
//Get the index of the clicked button
NSLog(#"%li", (long)sender.tag);
[self doSomething:(long)sender.tag];
}
Constants.h
#define ROW_BUTTON_ACTION 9
Why it is giving an incorrect index when I change the initial items of the tableView? Is there a way to solve this issue?
It looks like you're messing up button tags. Once you set the tag
lBtnWithAction.tag = indexPath.row;
you won't be able to get button correctly with
lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
(assuming ROW_BUTTON_ACTION is a constant). lBtnWithAction will be nil all the time except when indexPath.row is equal to ROW_BUTTON_ACTION.
I would propose to subclass UITableViewCell, add a button-property there and then just refer to it directly instead of searching by tag. In this case you'll be able to use tags for buttons freely :) –
#interface UIMyTableViewCell : UITableViewCell
#property (nonatomic, strong, nonnull) UIButton *lBtnWithAction;
#end
And then in cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UIMyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.lBtnWithAction addTarget:self action:#selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
cell.lBtnWithAction.tag = indexPath.row;
return cell;
}
You can simply update you line -
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
to
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]
My take on this will be subclassing the UITableViewCell and providing a delegate for it to respond.
code:
//MyCoolTablewViewCell.h
#protocol MyCoolProtocol<NSObject>
-(void)youTouchedMyCoolCell:(MyCoolTableViewCell __nonnull *)myCoolCell;
#end
#interface MyCoolTableViewCell:UITableViewCell
#property(nonatomic, weak,nullable) id<MyCoolProtocol>myCooldelegate;
#end
//MyCoolTablewViewCell.m
#interface MyCoolTableViewCell(){
UIButton *mySuperCoolButton;
}
#end
#implementation MyCoolTablewViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if(!(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])){
return nil;
}
// init your stuff here
// init button
mySuperCoolButton = [UIBUtton buttonWithType:UIButtonTypeCustom];
[mySuperCoolButton addTarget:self action:#selector(tappedMyCoolButton:) forControlEvents:UIControlEventTouchUpInside];
return self;
}
- (void)tappedMyCoolButton:(id)sender{
if([_myCoolDelegate respondToSelector:#selector(youTouchedMyCoolCell:)]){
[_myCoolDelegate youTouchedMyCoolCell:self];
}
}
#end
then in your controller
// whatEverController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// get the cell
cell = [tableView dequeueReusableCellWithIdentifier:#"myCoolIdentifier"forIndexPath:indexPath];
cell.myCooldelegate = self;
}
-(void)youTouchedMyCoolCell:(MyCoolTableViewCell *)myCoolCell{
NSIndexPath *myCoolIndexPath = [_tableView indexPathForCell:myCoolCell];
// then do whatever you want with the index path
}
In my app rows are added to my TableView from a different view. When the user adds the rows the user is taken back to the TableView. The problem is that the text that was previously entered is no longer shown.
I am able to load it with an NSMutableDictionary but the user cannot see it. Any ideas on what I should do? what code I should add and where I should add it? Thanks a lot!
Here is code from a tableview method. I think the fix will go in here somewhere.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.wtf = [[UITextField alloc]init];
NSUInteger count =0;
for (NSMutableDictionary *search in dataForAllRows){ //this just helps me pull the right data out of an array of NSMutableDictionary's
if ([search valueForKey:#"indexSection"] == [NSNumber numberWithInteger:(indexPath.section -1)]) {
if ([search valueForKey:#"indexRow"] == [NSNumber numberWithInteger:indexPath.row]) {
NSMutableDictionary *match = [dataForAllRows objectAtIndex:count];
[cell.wtf setText:[match objectForKey:#"wtf"]];
NSLog(#"%#",cell.wtf.text); // this outputs the correct value in the command line
}
}
count++;
}
}
}
Here is the code for my CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize wtf, cellPath;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)layoutSubviews{
wtf = [[UITextField alloc] initWithFrame:CGRectMake(7, 3, 65, self.contentView.bounds.size.height-6)];
self.wtf.delegate = self;
[wtf setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[wtf setAutocorrectionType:UITextAutocorrectionTypeNo];
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[wtf setBorderStyle:UITextBorderStyleRoundedRect];
wtf.textAlignment = NSTextAlignmentCenter;
wtf.keyboardType = UIKeyboardTypeNumberPad; //
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeWords];
[wtf setPlaceholder:#"enter"];
[self.contentView addSubview:wtf];
}
Consider defining the cell with identifier #"Cell" in IB as a prototype row of the table. Then, use dequeueReusableCellWithIdentifier:forIndexPath: to retrieve the cell in cellForRowAtIndexPath. It's easier to understand what your cells will look like, and you can avoid some mistakes that are common when defining subviews in code.
Speaking of common mistakes, your code appears to present a couple: it doesn't frame the text field, nor does it add it as a subview of the cell. Both would explain not seeing the text field.
#williamb's advice is correct and necessary: only build the cell's subview's if they are absent, but the building of the cell is incomplete...
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UITextField *wtf = [[UITextField alloc]initWithFrame:CGRectMake(10,10,200,42];
[wtf setDelegate:self];
[cell addSubview:wtf];
cell.wtf = wtf;
}
As I mentioned in comment, a sectioned table ought to be supported by a 2D array. The outer array is an array of sections. Each section array is an array of dictionaries equal to the ones you're searching each time through this method, but pre-arranged so all that's done in cellForRowAtIndexPath is indexing into an array:
NSDictionary *d = self.myCorrectlyStructuredModel[indexPath.section][indexPath.row];
cell.wtf.text = d[#"wtf"];
It's not a big challenge to build this from what you have. Consider doing this right after you solve the text field problem. I (or others) can give you some advice -- if you need any -- about how to build that structure.
It looks like you are only setting the text value of your textfield if that cell does not exist and overriding your textfield instance to one that does not have a frame as #danh mentioned. What I believe you want to do is reuse the textfield once it is added to your cell's contentview and change what that textfield shows for each index path.
Try refactoring your cell code to be more like:
#implementation ExerciseCell
#pragma mark - Init
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style
reuseIdentifier:reuseIdentifier];
if (self)
{
wtf = [[UITextField alloc] initWithFrame:CGRectMake(7, 3, 65, 44)];
wtf.delegate = self;
[wtf setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[wtf setAutocorrectionType:UITextAutocorrectionTypeNo];
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[wtf setBorderStyle:UITextBorderStyleRoundedRect];
wtf.textAlignment = NSTextAlignmentCenter;
wtf.keyboardType = UIKeyboardTypeNumberPad;
[wtf setAutocapitalizationType:UITextAutocapitalizationTypeWords];
[wtf setPlaceholder:#"enter"];
[self.contentView addSubview:wtf];
}
return self;
}
and your tableview datasource class to be more like
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.wtf setDelegate:self];
}
NSUInteger count = 0;
for (NSMutableDictionary *search in dataForAllRows){ //this just helps me pull the right data out of an array of NSMutableDictionary's
if ([search valueForKey:#"indexSection"] == [NSNumber numberWithInteger:(indexPath.section -1)]) {
if ([search valueForKey:#"indexRow"] == [NSNumber numberWithInteger:indexPath.row]) {
NSMutableDictionary *match = [dataForAllRows objectAtIndex:count];
[cell.wtf setText:[match objectForKey:#"wtf"]];
NSLog(#"%#",cell.wtf.text); // this outputs the correct value in the command line
}
}
count++;
}
}
}
Also do you mean to assign the the textField's delegate twice? Once in the cell and once in the tableview's datasource?
In order to load text into the UITextField in the CustomCell I added the following method
CustomCell.m
-(void)viewMyCellData{
//here I can set text to my textfield
wtf.text = #"Desired Text"; //this will read in every wtf textfield in the table
//getting the right text from an array will be asked in another question that I will post
//in a comment to this answer
}
Next we call this using [self viewMyCellData]
at the end of our
-(void)layoutSubviews method which is also in CustomCell.m
I've got a table view where the cells are created as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = #"TempTitle";
cell.textLabel.font = [UIFont fontWithName: #"AppleSDGothicNeo-Bold" size:16.0];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *numberLabel = [[UILabel alloc] init];
[numberLabel setFrame:CGRectMake(230.0, 5.0, 40.0, 30.0)];
[numberLabel setText:[NSString stringWithFormat:#"%#", [self.arrayOne objectAtIndex:indexPath.row]]];
UIButton *buttonDown = [[UIButton alloc] init];
[buttonDown setFrame:CGRectMake(190.0, 5.0, 40.0, 30.0)];
buttonDown.tag = indexPath.row;
[buttonDown addTarget:self action:#selector(quantityDown:) forControlEvents:UIControlEventTouchUpInside];
UIButton *buttonUp = [[UIButton alloc] init];
[buttonUp setFrame:CGRectMake(270.0, 5.0, 40.0, 30.0)];
[cell addSubview:buttonDown];
[cell addSubview:numberLabel];
[cell addSubview:buttonUp];
return cell;
}
where self.arrayOne (name changed for this thread) holds integer values that are displayed in each cell. The method when buttonDown is selected is as following:
- (void) quantityDown:(id)sender {
int clicked = ((UIButton *)sender).tag;
... math to lower int by one and save the new value in arrayOne
... this part works just fine. The value does go down, as intended.
[self.tableView reloadData];
}
When the tableView reloads, a new label is printed on top of the existing label in that cell, as can be seen in the image below:
I can only assume that new buttons are being printed on top of the existing ones as well. This is both expensive and makes the numbers unreadable (especially if you change it multiple times!). Leaving the view and coming back to it shows the new numbers cleanly, but only until you start changing them again.
A similar effect happens when I use the UISegmentedControl at the top. Selecting one or the other changes the contents of the table and runs [self.tableView reloadData]. The textLabel for each cell reloads just fine when this method is called, but the sub views do not reload, and instead stack upon one another.
How would I go about writing this so that there is only ever one subview in each cell, instead of multiple stacked upon one another? Something speedy and not expensive on resources. Maybe removing all subviews and then adding the new ones? I tried something like
[[cell.contentView viewWithTag:tagVariable]removeFromSuperview];
to no avail. Really, I only need to modify the one cell in the table that the user is clicking in. Except for when the user uses the UISegmentedControl at the top, then all the cells need to be modified.
Thanks in advance.
EDIT 1:
Created a custom UITableViewCell class...
#interface SSCustomTableViewCell : UITableViewCell
#property (nonatomic) UILabel *quantity;
#property (nonatomic) UIButton *down;
#property (nonatomic) UIButton *up;
#end
#implementation SSWeightsTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.quantity = [UILabel new];
[self.contentView addSubview:self.quantity];
self.down = [UIButton new];
[self.contentView addSubview:self.down];
self.up = [UIButton new];
[self.contentView addSubview:self.up];
}
return self;
}
- (void) layoutSubviews {
[super layoutSubviews];
[self.down setFrame:CGRectMake(190.0, 5.0, 40.0, 30.0)];
[self.down setBackgroundColor:[UIColor purpleColor]];
[self.up setFrame:CGRectMake(270.0, 5.0, 40.0, 30.0)];
[self.up setBackgroundColor:[UIColor purpleColor]];
[self.quantity setFrame:CGRectMake(230.0, 5.0, 40.0, 30.0)];
[self.quantity setTintColor:[UIColor purpleColor]];
}
#end
and then in my UITableView class...
#import "SSCustomTableViewCell.h"
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView
registerClass:[SSCustomTableViewCell class]
forCellReuseIdentifier:NSStringFromClass([SSCustomTableViewCell class])
];
}
and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier: NSStringFromClass([SSWeightsTableViewCell class])
forIndexPath:indexPath
];
}
but now all I see is the following...
where the subviews are not correctly laid out, nor are they the correct size. Also, within the cellForRowAtIndexPath method, I cannot access the cell's components. When I enter
cell.quantity
I get an error saying that "Property 'quantity' not found on object of type UITableViewCell*"
So I tried
SSCustomTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier: NSStringFromClass([SSWeightsTableViewCell class])
forIndexPath:indexPath
];
and the error goes away, but it still looks the same when I run it.
Edit 2: Working Solution
All I had to do was add
cell = [[UITableViewCell alloc]init];
within the cellForRowAtIndexPath method. Everything else stayed the same, and no custom classes required.
You are seeing this error because cell instances are reused. If you add a view each time you configure the cell, you will be adding to cells that already have the subviews on them. You should create your own subclass of UITableViewCell and add the subviews to it in init. Then your method above would just set the values on the various subviews.
Your cell would look something like this:
#interface MyCustomCell : UITableViewCell
#property (nonatomic, strong) UILabel *myCustomLabel;
#end
#implementation MyCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.myCustomLabel = [UILabel new];
[self.contentView addSubview:self.myCustomLabel];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Arrange self.myCustomLabel how you want
}
#end
Then your view controller would look like this:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView
registerClass:[MyCustomCell class]
forCellReuseIdentifier:NSStringFromClass([MyCustomCell class])
];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:NSStringFromClass([MyCustomCell class])
forIndexPath:indexPath
];
cell.myCustomLabel.text = #"blah";
return cell;
}
Try this in cell configure method, this will make sure objects doesn't overlap
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
example:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
return cell;
}
Hope this will help
I'm trying to to something like apple's alarm clock, when tap the edit button, a custom view cover the custom UITableViewCell.
The code above:
// CGRect frame = [tableView rectForRowAtIndexPath:indexPath];
// CGPoint yOffset = self.tableViewBlock.contentOffset;
// CGRect newFrame = CGRectMake(frame.origin.x, (frame.origin.y - yOffset.y + 45), frame.size.width, frame.size.height);
CallBlock_Date_EditMode *viewController = [[CallBlock_Date_EditMode alloc] initWithNibName:#"CallBlock_Date_EditMode" bundle:nil];
// self.view.frame = newFrame;
// [self.view addSubview:viewController.view];
// [self addChildViewController:viewController];
UITableViewCell *cell = (UITableViewCell*)[self.tableViewBlock cellForRowAtIndexPath:indexPath];
[cell.contentView addSubview:viewController.view];
Cover the specific cell when I put in under:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Just to make sure the size is ok (although when I tap a button in that xib the app crash without even a single error).
But I want to do like apple's alarm clock (actually, mimic it), tap my edit button and my custom UITableViewCell will get cover with this xib as a view.
Maybe there is a better approach to do it?
EDIT:
My updated code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CallBlock_TableCell *cell = (CallBlock_TableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[CallBlock_TableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(CallBlock_TableCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryType = self.isEditing ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
CallBlock_ByDate *callBlock = (CallBlock_ByDate*)[fetchedObjects objectAtIndex:indexPath.row];
cell.labelTime.text = callBlock.startDate;
cell.labelRepeat.text = callBlock.repeat;
cell.labelTextLabel.text = callBlock.label;
cell.switchCallBlock.on = YES;
cell.switchCallBlock.tag = (NSInteger)indexPath.row +1;
[cell.switchCallBlock addTarget:self action:#selector(handleSwitch:) forControlEvents:UIControlEventValueChanged];
cell.switchCallBlock.hidden = self.isEditing ? YES : NO;
if (self.isEditing)
{
cell.switchCallBlock.hidden = YES;
UIButton *btnArrow = [[UIButton alloc] init];
btnArrow.frame = CGRectMake(282.0, 31.0, 18.0, 21.0);
[btnArrow setBackgroundImage:[UIImage imageNamed:#"arrow_FWR_off"] forState:UIControlStateNormal];
[btnArrow setBackgroundImage:[UIImage imageNamed:#"arrow_FWR_on"] forState:UIControlStateHighlighted];
btnArrow = [UIButton buttonWithType:UIButtonTypeCustom];
[btnArrow addTarget:self action:#selector(handleTapToEdit:) forControlEvents:UIControlEventTouchUpInside];
btnArrow.tag = indexPath.row + 1;
[cell.contentView addSubview:btnArrow];
[cell.contentView bringSubviewToFront:btnArrow];
}
}
But I cannot get the btnArrow appear on the UTableView.
The reason you are getting a crash is because nothing is retaining your CallBlock_Date_EditMode view controller. You add its view to your cell as a subview, but nothing maintains a reference to the view controller, so it is deallocated and then, when pressing a button that is supposed to pass a message to your view controller, it is sent to a deallocated object and you get a crash.
There are two possible solutions to this. First, you could store that view controller in one of your properties to maintain a reference to it so that it does not deallocated. This is, for the most part, probably not what you want.
Instead, what I would suggest doing is do not make your CallBlock_Date_EditMode a UIViewController, but instead make it a UIView. You may be wondering "But how can I use a xib without a UIViewController?". I would do something like the following:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UIView *view = [[[NSBundle mainBundle] loadNibNamed:#"CallBlock_Date_EditMode" owner:self options:nil] objectAtIndex:0];
self.myEditButton = (UIButton *)[view viewWithTag:2];
[self addSubview:view];
}
return self;
}
This would be code inside your custom UIView that would load in a xib file and add it as a subview. In order to get access to your subviews, you have to use tags inside interface builder, so you do lose the convenience of drawing/connecting IBOutlets... But in the end, it is much better than allocating/storing a bunch of unnecessary UIViewControllers.
If I understand you right and you want to mimic the functionality of the alarm clock that comes pre-installed from Apple, your solution is much simpler than creating a custom view. It looks like all they do is set the On-Off switches to hidden and add a disclosure indicator to the cell. This is what I would do...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
bool hide = (tableView.editingStyle == UITableViewCellEditingStyleDelete); // set to true or false depending on if the table is in editing mode
for (UIView *sv in [cell subviews] ) {
if([sv isKindOfClass:[UISwitch class]]) { // find the on-off switch
[sv setHidden:hide]; // hide the switch depending on the t/f value of hide
break;
}
}
if(hide) { // adds the arrow like in apple's alarm clock table if the cell is in edit mode
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
else {
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
return cell;
}
I made a custom UITableViewCell in Interface Builder (Storyboard) and imported it to my project via #import CustomTableViewCell.h.
Everything works fine, but the cell is only loaded in selected state.
I want the cell to be loaded in every row by init.
P.S. The slider and text field connections work fine. I also made all of the IB Connections.
CustomTableViewCell.m
#import "CustomTableViewCell.h"
#implementation CustomTableViewCell
#synthesize sliderLabel, slider;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (IBAction)getSliderValuesWithValue:(UISlider *)sender
{
sliderLabel.text = [NSString stringWithFormat:#"%i / 100", (int) roundf(sender.value)];
}
#end
Further Code
- (CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Kriterium";
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%#", [listOfItems objectAtIndex:indexPath.row]];
return cell;
}
P.S. If I add some Buttons etc. programmatically in the above method it works. But I want to design the rows in IB. There has to be a solution.
Okay ... strange things happening here ... ;-) The problem was this line:
cell.textLabel.text = [NSString stringWithFormat:#"%#", [listOfItems objectAtIndex:indexPath.row]];
Leaving it out did the trick. I had to add another UILabel to my CustomCell which I fill with text.
CONCLUSION
Filling the standard UITableViewCell.textLabel.text seems to overwrite the PrototypeCells.
... too much customization hurts. ;-)
Thanks anyway! :)
Suggesting you to not go for IB. Just define those controls as property and in your init method- initWithStyle(CustomTableViewCell.m file) initialize UISlider with its default property:
UISlider *tempSlider = [[UISlider alloc] initWithFrame:frame];
tempSlider.selected = NO;
//define other properties as well
self.slider = tempSlider;
[self addSubview:self.slider];
[tempSlider release];
Besides you can also set cell selection style to none.
cell.selectionStyle = UITableViewCellSelectionStyleNone;