I want to add a button in a UITableViewCell. This is my code: `
if (indexPath.row==2) {
UIButton *scanQRCodeButton = [[UIButton alloc]init];
scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.backgroundColor = [UIColor redColor];
[scanQRCodeButton setTitle:#"Hello" forState:UIControlStateNormal];
[cell addSubview:scanQRCodeButton];
}`
Now, when I run the app, I see only a blank row ! Any ideas ?
While it's natural to put it in the contentView of the cell, I'm fairly certain that is not the problem (actually, in the past, I've never had subviews displayed correctly in the contentView, so I've always used the cell).
Anyway, the problem involves the first three lines of when you start creating your button. The first two lines are fine, but the code stops working with:
scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonWithType: is actually a convenience method to create a button (it's like a compact alloc-init). Therefore, it actually "nullifies" your past two lines (you basically created the button twice). You can only use either init or buttonWithType: for the same button, but not both.
UIButton *scanQRCodeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
scanQRCodeButton.frame = CGRectMake(0.0f, 5.0f, 320.0f, 44.0f);
scanQRCodeButton.backgroundColor = [UIColor redColor];
[scanQRCodeButton setTitle:#"Hello" forState:UIControlStateNormal];
[cell addSubview:scanQRCodeButton];
This will work (note that you can use cell.contentView if you wanted). In case you're not using Automatic Reference Counting (ARC), I would like to mention that you don't have to do anything in term of memory management, because buttonWithType: returns an autoreleased button.
UIButton *deletebtn=[[UIButton alloc]init];
deletebtn.frame=CGRectMake(50, 10, 20, 20);
deletebtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[deletebtn setImage:[UIImage imageNamed:#"log_delete_touch.png"] forState:UIControlStateNormal];
[deletebtn addTarget:self action:#selector(DeleteRow:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deletebtn];
or
// Download class and import in your project UIButton+EventBlocks
UIButton *deletebtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[deletebtn setFrame:CGRectMake(170,5, 25, 25)];
deletebtn.tag=indexPath.row;
[deletebtn setImage:[UIImage imageNamed:#"log_delete_touch.png"] forState:UIControlStateNormal];
[deletebtn setOnTouchUpInside:^(id sender, UIEvent *event) {
//Your action here
}];
[cell addSubview:deletebtn];
You want to add any custom UI elements to the cell's contentView.
So, instead of [cell addSubview:scanQRCodeButton];
do [cell.contentView addSubview:scanQRCodeButton];
Try adding [cell.contentView addSubview:scanQRCodeButton]; or if you want the button to the left side look at my question at the answer, to move the textLabel to the side. If you want the button to the right then just set it as your accesoryView like this cell.accesoryView = scanQRCodeButton;.
Method setTitle does not work in my code, so I have set by using
[UIButton.titleLabel setText:#""]
instead of using setTitle method.
Please try again with following code:
[scanQRCodeButton.titleLabel setText:#"Hello"];
Then it would work well.
Related
I have an iPhone app problem that's been bugging me for a few days and it really doesn't seem like it should be this difficult so I'm sure I'm missing something obvious. I have researched plenty of forum discussions on "similar" topics but nothing that actually addresses this issue, specifically.
To be clear, if there is some piece of documentation or some other source that I should research, please point me in the right direction.
Here goes...
I have a list of items that I display to the user within a table (uitableview). The cell (uitableviewcell) for each item is custom and contains two image buttons(uibuttons: green and red). As expected, for each item in the the table, the user can click any of the buttons. Based on a parameter called monitoringRequestType for a button, the button calls a separate process to update the server. If the state is "Approved",the image changes to 'alreadyapproved' and 'reject' respectively. So when I click on the red button, server updates the state to "Rejected" and image then changes to 'approve' and 'alreadyrejected'.
Simple, right?
So, here is the issue:
On clicking the reject button, the 'approve' image comes on top of the 'alreadyapproved' image (so both images can be seen) while 'alreadyrejected' image works fine.For brevity, I am only including the relevant code here (hopefully formatted properly):
CellForRow:
if(indexPath.section==0){
NSDictionary *dict=[saveJson objectAtIndex:indexPath.row];
NSString* sMonitoringType = [dict valueForKey:#"monitoringType"];
UIButton *button1= [[UIButton alloc] initWithFrame:CGRectMake(230,10,40,40)];
UIButton *button2= [[UIButton alloc] initWithFrame:CGRectMake(280,10,40,40)];
if([sMonitoringType compare:#"Pending"] == NSOrderedSame){
[button1 setImage:[UIImage imageNamed:#"approve"]
forState:UIControlStateNormal];
[button1 addTarget:self
action:#selector(greenButtonPressed:withEvent:)
forControlEvents:UIControlEventTouchUpInside];
button1.tag= indexPath.row;
[button2 setImage:[UIImage imageNamed:#"reject"]
forState:UIControlStateNormal];
[button2 addTarget:self
action:#selector(redButtonPressed:withEvent:)
forControlEvents:UIControlEventTouchUpInside];
button2.tag= indexPath.row;
} else if([sMonitoringType compare:#"Approved"] == NSOrderedSame){
[button1 setImage:[UIImage imageNamed:#"alreadyapproved"]
forState:UIControlStateNormal];
[button2 setImage:[UIImage imageNamed:#"reject"]
forState:UIControlStateNormal];
[button2 addTarget:self
action:#selector(redButtonPressed:withEvent:)
forControlEvents:UIControlEventTouchUpInside];
button2.tag= indexPath.row;
} else if([sMonitoringType compare:#"Rejected"] == NSOrderedSame){
[button1 setImage:[UIImage imageNamed:#"approve"]
forState:UIControlStateNormal];
[button2 setImage:[UIImage imageNamed:#"alreadyrejected"]
forState:UIControlStateNormal];
[button1 addTarget:self
action:#selector(greenButtonPressed:withEvent:)
forControlEvents:UIControlEventTouchUpInside];
button1.tag= indexPath.row;
}
[cell addSubview:button1];
[cell addSubview:button2];
[button1 release];
[button2 release];
}
return cell;
}
The UIButtons are being added to the cell's subview whenever the cell reloads (you're reusing cells, right?). You should reuse the older buttons already added to the cell's subview instead of adding new ones and just to verify the issue, stop reusing the cells (memory inefficient, should not be done in production code!). To reuse the older buttons, set a unique tag for each button and get them back as [cell viewWithTag:uniqueTag]
if(indexPath.section==0){
NSDictionary *dict=[saveJson objectAtIndex:indexPath.row];
NSString* sMonitoringType = [dict valueForKey:#"monitoringType"];
UIButton *button1= [cell viewWithTag:900];
UIButton *button2= [cell viewWithTag:901];
if(!button1){// button1 doesn't exist yet (first time)
button1 = [[UIButton alloc] initWithFrame:CGRectMake(230,10,40,40)];
[cell addSubview:button1];
}
if(!button2){// button2 doesn't exist yet (first time)
button1 = [[UIButton alloc] initWithFrame:CGRectMake(280,10,40,40)];
[cell addSubview:button2];
}
......
I want my UIButton to always stay on bottom of screen without adjusting the X all the time. Here is my code that hides my button in horizontal mode.
UIImage *greenBtnImage = [[UIImage imageNamed:#"green-btn-iphone.png"]stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
bt = [UIButton buttonWithType:UIButtonTypeCustom];
[bt setBackgroundImage:greenBtnImage forState:UIControlStateNormal];
bt.frame = CGRectMake(14.0f,406.0f,292.0f,41.0f);
[bt addTarget:self action:#selector(didClickButton:)
forControlEvents:UIControlEventTouchUpInside];
[bt setTitle:#"OK" forState:UIControlStateNormal];
bt.autoresizingMask = (UIViewAutoresizingFlexibleWidth);
bt.autoresizesSubviews = YES;
[self.view addSubview:bt];
I have trouble finding answer how to do it programmatically. Thank you.
If I understood you well, this should help:
bt.autorezisingMask = UIViewAutoresizingFlexibleTopMargin;
Disclaimer: I never did that myself programmatically so far, used autorezising only in conjunction with the Interface Builder.
I am using the StoryBoard feature for my iPhone project. In the storyboard, I have a view controller with a table view using prototype cells. Inside the prototype cell, I have a UIButton (rounded rectangle) hooked up to a sub-classed UIButton class. The tableview gets its data from an array, and the data is printed out in cellForRowAtIndexPath.
Inside cellForRowAtIndexPath, I conditionally modify the cell's appearance. This is when I start getting problems. I am able to successfully change the text of the button. However, if I attempt to change the image of the button, using:
[cell.myButton setImage:[UIImage imageNamed:#"mynewimage.png"] forState:UIControlStateNormal];
the image is changed, but the text disappears.
If I attempt to change the text color of the button, using:
[cell.myButton setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.77] forState:UIControlStateNormal]
Nothing happens whatsoever. The color remains the same (unless I also try to change the image, in which case it completely disappears).
I am sensing I am doing something fundamentally wrong here -- do you have any suggestions?
use
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
to change image with text left
use
btn.titleLabel.textColor = yourcolor;
to change text color
Define myButton as below and check.This may be the wrong in your code.The code is:
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
This is newly editted part:
[myButton setBackgroundImage:yourimage forState:UIControlStateNormal];
[myButton setTitleColor:yourcolor forState:UIControlStateNormal];
This is the way to set different properties to a Custom Button...You also find that setBackgroudimage and setTitleColor properties here...
UIButtin *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(165, 205, 65, 40)];
[myButton setTitleColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.77] forState:UIControlStateNormal];
[myButton setTitle:#"Hi....." forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[myButton setBackgroundImage:[UIImage imageNamed:#"mynewimage.png"] forState:UIControlStateNormal];
[cell addSubview:myButton];
Thank u..
I guess what you want is to change your button background:
[cell.myButton setBackgroundImage:[UIImage imageNamed:#"mynewimage.png"] forState:UIControlStateNormal];
Your text disappears because you have set the image at button front side as button main image.
[cell.myButton setImage:[UIImage imageNamed:#"mynewimage.png"] forState:UIControlStateNormal];
You need to set the button background image so that your text would be visible as the image will be drawn at the rear side of your UIButton context.
So just replace the above line of code to :
[cell.myButton setBackgroundImage:[UIImage imageNamed:#"mynewimage.png"] forState:UIControlStateNormal];
I have added uibutton in a cell in uitable view. I want this button to be pressed and interat with user. I added this line of code in cell implementation class.
readMore = [[UIButton alloc]initWithFrame: CGRectMake(180, 50, 67, 25)];
[readMore addTarget:self action:#selector(readMoreClic:) forControlEvents:UIControlEventTouchUpInside];
[readMore setImage:[UIImage imageNamed:#"readmore.png"] forState:UIControlStateNormal];
[self addSubview:readMore];
the problem is that it is not clicked (it is always in highlight state after selecting the cell). I tried :-
1- [self setSelectionStyle:UITableViewCellSelectionStyleNone];
2- cell.userInteractionEnabled = NO
but I still get cells selected and highlighted with blue color and button not clicked. even after i've chosen
[self setSelectionStyle:UITableViewCellSelectionStyleGray]
some one help plz
thx
[note i have a textView in the same cell and it allows interaction (select and copy) ]
[i am using xcode 4 with iOS 4.3]
try a different control event?:
[readMore addTarget:self action:#selector(readMoreClic:) forControlEvents:UIControlEventTouchDown];
well, i don't quite understand why your button don't respond, because i've came across similar problems but i've used different solutions. here's what i've done:
CGRect reuseableRect = CGRectMake(20, 290, 260, 37);
self.actionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.actionButton.frame = reuseableRect;
[self.actionButton setTitle:#"Initialize" forState:UIControlStateNormal];
[self.actionButton addTarget:nil action:#selector(performAction) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.actionButton];
Actually, i did this :
self.actionButton = [[UIButton alloc] initWithFrame:reuseableRect];
but it didn't work. so i changed it into
self.actionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
the resueableRect is just a CGRect that I've used all through the view initialization.
as for the three lines of your previous solution, the first one:
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
it's doing some configurations to the tableView and its cells, so it's not going to affect the button
the second one:
cell.userInteractionEnabled = NO;
it's not configuring the button as well, what's more, since the cell is the super view of the button, this line prevents any user interactions.
the third one is not doing anything to the button as well, so i recommend that you delete all of them if you were thinking about configuring the button
You don't need to do anything with selection style or userInteractionEnabled. Make sure that readMoreClic: looks like:
-(void)readMoreClic:(id)sender
{
}
this is driving me MAD now.. I have a UItableview. Based on an NSMutableArray, I populate it.
I set up in reuseTableViewCellWithIdentifier with the following
cellRectangle = CGRectMake((ARROW_OFFSET + 5), (ROW_HEIGHT - LABEL_HEIGHT) / 2.0, ARROW_WIDTH, LABEL_HEIGHT);
UIButton *tmpButton = [[UIButton alloc] initWithFrame:cellRectangle];
[tmpButton initWithFrame:cellRectangle];
[tmpButton setImage:[UIImage imageNamed:#"icon_edit.png"] forState:UIControlStateNormal];
[tmpButton setImage:[UIImage imageNamed:#"icon_no.png"] forState:UIControlStateDisabled];
[tmpButton addTarget:self action:#selector(editSelectedRow:) forControlEvents:UIControlEventTouchUpInside];
tmpButton.tag = ARROW_TAG;
[cell.contentView addSubview: tmpButton];
[tmpButton release];
then in cellForRowAtIndexPath I have the following lines of code
UIButton *button = (UIButton *)[cell viewWithTag:ARROW_TAG];
[button setTag:indexPath.row];
if (counterHasStarted == 1) {
NSLog(#"yes");
button.enabled = NO;
} else {
button.enabled = YES;
}
the button shows nicely, but for some reason when the counterHasStarted variable (which is an int is set, it doesn't change! I can change UILabels based on the above code (checking if counterHasChanged is 1 or 0).
Any ideas what's going on??
-cellForRowAtIndexPath: will only get called when the table view needs a new UITableViewCell because the user scrolled.
I guess you're changing counterHasStarted and expect the button enabled state to change? You could reload the data when you change counterHasStarted ([yourTableView reloadData]). Then the table view will call -cellForRowAtIndexPath: for all the cells that are currently visible, and you can enable or disable the buttons as needed.