text not visible after moving UIButtons - ios

float newY = 0;
CGRect buttonFrame;
for(int i=1; i<=countTabItems;i++){
id item = [self viewWithTag:i];
if([item isKindOfClass:[UIButton class]]){
UIButton *button = item;
[item release];
NSLog(#"got %#", button.titleLabel.text);
buttonFrame = button.frame;
buttonFrame.size.height = self.frame.size.height/countTabItems;
buttonFrame.size.width = self.frame.size.width;
buttonFrame.origin.x = 0;
buttonFrame.origin.y = newY;
button.frame = buttonFrame;
[button setTitle:#"TEST" forState:UIControlStateNormal];
NSLog(#"%0.2f",newY);
[button release];
newY += frame.size.height/countTabItems;
}
}
Can someone tell me what is problem with this code, please. I use this to move buttons from their original position after which the UIButton is not showing any Title (text) on it.

[self viewWithTag:i]; does not retain anything so the release of item object should not be there. The same goes for the release of the button object. Try to remove those two releases and see if it solves your problem.

Related

getting element from array one by one and createbutton

I have a UItextFeild as search bar on clicking a tableview with suggestion open.now i want to click on that row and make a button with its label in below view as described in image .how can i acheive this
I want it one by one means when i click on row it create a button on view and UITableView hide then again i start searching and on again clicking on some other row make a button with different value of X.
_selectednames = [NSMutableArray arrayWithCapacity:self.sortedArray.count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MGContactItemsModel *model = _arrayForContacts[indexPath.row];
self.searchText.text = [NSString stringWithFormat:#"%#",[_sortedArray objectAtIndex:indexPath.row]];
self.tableView.hidden = YES;
[_selectednames addObject:_searchText.text];
for (int i; i < _selectednames.count ; i++) {
[self makeLabelsAndButtons:i];
}
now in my makeLabelsAndButtons funtion i done something like this
CGFloat xOffset = 10.0f;
int buttonCount = 0;
CGRect buttonFrame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
NSString *nameString = [self.selectednames objectAtIndex:indexPath];
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
//_button.frame = CGRectMake(xOffset, 10.0, 50.0, 15.0);
for(int i=buttonCount; i >0;i++) {
xOffset = xOffset+10;
buttonFrame.origin.x += buttonFrame.size.width+xOffset;
}
_button.frame = buttonFrame;
buttonCount++;
_button.tag = indexPath;
//button.center = CGPointMake(xOffset, 10.0f);
//[button setBackgroundImage:[UIImage imageNamed:picString] forState: UIControlStateNormal];
[_button setTitle:self.selectednames[indexPath] forState:UIControlStateNormal];
_button.backgroundColor = [UIColor lightGrayColor];
_button.titleLabel.font = [UIFont fontWithName:#"Arial" size:8.0f];
_button.layer.cornerRadius = 10.0f;
_button.layer.masksToBounds = YES;
[self.buttonView addSubview:_button];
NSLog(#"name: %#", nameString);
also on clicking button it will removed.any help would be thankful.
It works for me.Please try it.
y=20;
x=20;
for (int i=0; i<[arrAssignUsers count]; i++) {
CGRect screenRect=[[UIScreen mainScreen]bounds];
CGFloat screenWidth=screenRect.size.width;
[arrBtnStatus addObject:[NSNumber numberWithBool:NO]];
NSString *strNames=[arrAssignUsers objectAtIndex:i];
stringsize=[strNames sizeWithAttributes:
#{NSFontAttributeName: [UIFont systemFontOfSize:20.0f]}];
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
CGFloat m=x+stringsize.width+10;
CGFloat n=screenWidth-20;
if (m<=n) {
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width +10;
}
else
{
y=y+stringsize.height+10;
x=20;
btn.frame=CGRectMake(x, y,stringsize.width,stringsize.height);
x=x+stringsize.width+10;
}
[btn setTitle:self.arrAssignUsers[i] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btn.tag=i;
[btn addTarget:self
action:#selector(notifyButtonPressedInEditTask:) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor=WHITE_COLOR;
btn.layer.cornerRadius=10;
[btn.layer setMasksToBounds:YES];
btn.layer.borderWidth=2.0f;
btn.layer.borderColor=[UIColor orangeColor].CGColor;
[self checkNotifybtnStatus:btn];
[cell addSubview:btn];
}
}
It may helps to you.Thank you
You can use UICollectionView to create buttons. All you need to do is
1. Create custom cell with button as you want
2. When you tap on table view cell, add item to array and reload UICollectionView
3. Show buttons and it will automatically add scrollview for you.
When you tap on UICollectionView cell, remove object from array and reload UICollectionView again.
This will more easy as compared to adding buttons and setting frames.
And design UICollectionView cell in such way that it will same length as your text, use NSLayoutConstraints for it. It will work fast and smooth.
Code will be minimum and reusable.
Try out this working code...
Take UIScrollView in your Xib for buttons
//Adding menu buttons
btnArray = #[#"SYMPTOMATIC", #"SOCIAL", #"VOCATIONAL", #"PERSONAL"];
[self addButtonsInScrollMenu:btnArray];
/**
* Add Menu Buttons in Menu Scroll View
*
* #param buttonArray Array containing all menu button title
*/
#pragma mark - Add Menu Buttons in Menu Scroll View
-(void) addButtonsInScrollMenu:(NSArray *)buttonArray
{
CGFloat buttonHeight = self.menuScrollView.frame.size.height;
CGFloat cWidth = 0.0f;
for (int i = 0 ; i<buttonArray.count; i++)
{
NSString *tagTitle = [buttonArray objectAtIndex:i];
CGFloat buttonWidth = [self widthForMenuTitle:tagTitle buttonEdgeInsets:kDefaultEdgeInsets];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(cWidth, 0.0f, buttonWidth, buttonHeight);
[button setTitle:tagTitle forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:#"Roboto-Regular" size:12.0f];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.menuScrollView addSubview:button];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height - kButtonBorderHeight, button.frame.size.width, kButtonBorderHeight)];
bottomView.backgroundColor = [UIColor darkTextColor];
bottomView.tag = 1001;
[button addSubview:bottomView];
if (i == 0)
{
button.selected = YES;
[bottomView setHidden:NO];
}
else
{
[bottomView setHidden:YES];
}
cWidth += buttonWidth;
}
NSLog(#"scroll menu width->%f",cWidth);
self.menuScrollView.contentSize = CGSizeMake(cWidth, self.menuScrollView.frame.size.height);
}

Bringing UiScrollView element to center when clicked

What I have is UIScrollView and inside it I have buttons of different different sizes.
- (void)viewDidLoad {
[super viewDidLoad];
myScrollView.frame = CGRectMake(0, 100, 375, 50.0);
int totalButtonsToAdd = 20;
startX = 0;
int buttonWidth = 60;
for (int i=0;i<totalButtonsToAdd;i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[NSString stringWithFormat:#"Btn-%d", i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
button.accessibilityValue = [NSString stringWithFormat:#"%d", i+1];
button.frame = CGRectMake(startX, 0, buttonWidth, 50.0);
[[button layer] setBorderWidth:2.0f];
[[button layer] setBorderColor:[UIColor greenColor].CGColor];
button.layer.cornerRadius = 5;
startX = startX + buttonWidth + 5;
buttonWidth = buttonWidth + 5;
[myScrollView addSubview:button];
}
NSLog(#"startX===%d", startX);
myScrollView.contentSize = CGSizeMake(startX, 50.0);
}
-(IBAction)aMethod:(id)sender {
UIButton *mButton = (UIButton *)sender;
NSLog(#"clicked button index is %#", mButton.accessibilityValue);
}
What I want to do is when I click any button, I want to bring that button in center. For this I believe I will need to scroll the scrollview to specific position.
For this what I did is as below.
- (void)viewDidLoad {
[super viewDidLoad];
myScrollView.frame = CGRectMake(0, 100, 375, 50.0);
int totalButtonsToAdd = 20;
startX = 0;
int buttonWidth = 60;
for (int i=0;i<totalButtonsToAdd;i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[NSString stringWithFormat:#"Btn-%d", i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
button.accessibilityValue = [NSString stringWithFormat:#"%d", i+1];
button.frame = CGRectMake(startX, 0, buttonWidth, 50.0);
[[button layer] setBorderWidth:2.0f];
[[button layer] setBorderColor:[UIColor greenColor].CGColor];
button.layer.cornerRadius = 5;
startX = startX + buttonWidth + 5;
NSLog(#"startX===%d==%d", i, startX);
buttonWidth = buttonWidth + 5;
[myScrollView addSubview:button];
}
NSLog(#"startX final===%d", startX);
myScrollView.contentSize = CGSizeMake(startX, 50.0);
}
-(IBAction)aMethod:(id)sender {
UIButton *mButton = (UIButton *)sender;
NSLog(#"clicked button index is %#", mButton.accessibilityValue);
focusPosition = 0;
int totalButtonsToAdd = 20;
int buttonWidth = 60;
startX = 0;
for (int i=0;i<totalButtonsToAdd;i++) {
startX = startX + buttonWidth + 5;
buttonWidth = buttonWidth + 5;
if (i==[mButton.accessibilityValue intValue]) {
focusPosition = startX;
}
}
NSLog(#"focusPosition===%d", focusPosition);
CGRect frame = CGRectMake(focusPosition, 0, buttonWidth, 50); //wherever you want to scroll
[myScrollView scrollRectToVisible:frame animated:NO];
}
However this don't give me exact what I want. Is there any property for scrollview that will bring that button in center?
Project with above code
Note: This is sample for iPhone 6 only. So please run project on iPhone 6 simulator only
UICollectionView would probably have been a better choice than a UIScrollView, since it adds a method to achieve just what you want (scrollToItemAtIndexPath:atScrollPosition:animated:).
If you're sticking with UIScrollView, you'll need to use setContentOffset:animated: instead, and compute the desired offset, e.g.:
-(IBAction)aMethod:(UIButton *)button {
CGPoint contentOffset = CGPointMake(CGRectGetMidX(button.frame) - (CGRectGetWidth(self.scrollView.frame) / 2.0),0.0);
[myScrollView setContentOffset:contentOffset animated:YES];
}
The UIScrollView function
- (void)scrollRectToVisible:(CGRect)rect
animated:(BOOL)animated
does almost that.
Reference says: "This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing."
Sorry, just saw you've already found that function.
Here is the link of a sample project which is doing the same as you want.
This include one class named PagedFlowView.
sample project to center a view in scrollview

get tag of UIButton and those with smaller tags

I'm not understanding if what I'm trying to do is possible or not.
I am creating buttons in for loop:
CGRect rect2 = CGRectMake(50, 230, 40, 40);
for (int i = 0; i<5; i++) {
NSString *stringI = [NSString stringWithFormat:#"%d",i+1];
NSString *stringItouch = [NSString stringWithFormat:#"%dselected",i+1];
UIButton *button = [[UIButton alloc] init];
[button setBackgroundImage:[UIImage imageNamed:stringI] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:stringItouch] forState:UIControlStateSelected];
[button addTarget:self action:#selector(touchButton:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i+1;
button.frame = rect2;
rect2.origin.x = rect2.origin.x + 45;
[scrollView addSubview:button];
}
and after in method touchButton i get the tag of touched button
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
}
}
in the last loop i want to select the buttons that have the tag less than that touched (in this case 3,2,1)
is it possible or not???
thanks everybody
All you need is viewWithTag: like so:
-(void)touchButton:(id)sender {
UIButton *buttonSender = sender;
buttonSender.selected = YES;
NSLog(#"button tag %#",buttonSender.tag);
for (int i = buttonSender.tag-1; i>0; i--) {
NSLog(#"int = %d",i);
//for example if buttonSender.tag is 4, in this way i have 3,2,1
/* Add this line */
UIButton *tempButton = (UIButton *)[scrollView viewWithTag:i];
}
}

Creating UIButton programmatically with custom class

I want to create 3-4 buttons programmatically but with a custom class and a specific value/key pair, but I struggle on how to do this exactly.
The button I want to create must have a custom class named "AnswerButton". Adding a UIButton.tag shouldnt be a problem, so I can exactly tell what button has been clicked, right?
Here is the code I use to create buttons:
NSMutableArray *catNames;
catNames = [NSMutableArray arrayWithCapacity:5];
[catNames addObject:#"Boote"];
[catNames addObject:#"Gewässer"];
[catNames addObject:#"Technik"];
[catNames addObject:#"Krims Krams"];
[self dynamiclyCreateButtons:4 :catNames];
- (void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
//Edit
What I mean by custom class:
https://i.stack.imgur.com/8r2oz.png
//Edit 2 (The correct answer, since I cannot post an answer myself to point it out better)
Just here to point it out and find the answer easier: Answer by Greg is correct.
You shouldn't create the buttons with the default class but with your custom class instead:
Replace
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
with
AnswerButton *catBtn = [AnswerButton buttonWithType:UIButtonTypeRoundedRect];
Dont forget to import the class!
Try This...
-(void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTag:i];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
- (IBAction)buttonClicked:(id)sender
{
NSLog(#"Button.Tag = %d",[sender tag]);
}
EDIT: If you want to use the custom class, you have to create a class inherited from UIButton. Then import this class in your view controller.
After that replace UIButton with YourCustomButton like..
YourCustomButton *catBtn = [YourCustomButton buttonWithType:UIButtonTypeRoundedRect];

How could I make this work with UIScrollView?

I'm inserting dynamically anywhere from 1 to 300 buttons inside a UIScrollView(as subviews). Currently, the buttons line up nicely but is not scrolling as I'd like them to. It just scrolls horizontally without a paging effect. Ideally, they way I'd like it to work is:
Display a max of 48 buttons per "page"
When scrolling to the right, show next "page" with 48 additional buttons
My code:
-(void)populateScrollView:(NSMutableArray *)colors {
// Properties
NSInteger count = 0;
NSInteger rowsize = 48;
CGFloat pageNum = 6;
CGFloat pageWidth = scrollView.frame.size.width;
CGFloat pageHeight = scrollView.frame.size.height;
CGFloat visibleWidth = 465;
myButtons = [[NSMutableArray alloc]init];
// Clear the subviews if any
for (UIView *subview in scrollView.subviews) {
[subview removeFromSuperview];
}
for (Color *element in colors) {
// Set the button properties
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:#"color_overlay.png"];
[button setImage:image forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateHighlighted];
div_t temp = div(count, rowsize);
button.frame = CGRectMake(52 * temp.rem , 52*temp.quot, 52, 52);
button.tag = count++;
UIImage *effect = [UIImage imageNamed:element.image_resource];
effectImage = [[UIImageView alloc] initWithImage:effect];
effectImage.frame = CGRectMake(52 * temp.rem , 52*temp.quot, 52, 52);
// Color the graphic if color available. If not, load the image
unsigned result = 0;
if ([element.hex_value length] > 1){
NSScanner *scanner = [NSScanner scannerWithString:element.hex_value];
[scanner scanHexInt:&result];
button.backgroundColor = UIColorFromRGB(result);
}
else {
effectImage.image = effect;
}
// Set actions for the color
[button addTarget:self action:#selector(changeGraphicColor:) forControlEvents:UIControlEventTouchUpInside];
[myButtons addObject:button];
for (UIButton *myButton in myButtons){
[scrollView insertSubview:effectImage atIndex:1];
[scrollView insertSubview:myButton atIndex:2];
}
}
// Set scrollView contentSize and create pages:
CGFloat leftShift=floor(((visibleWidth-pageWidth)/2)/pageWidth)*pageWidth;
CGFloat contentSizeReduction=2*leftShift;
scrollView.contentSize = CGSizeMake(pageNum*pageWidth-contentSizeReduction,pageHeight);
[myButtons removeAllObjects];
[myButtons release];
}
I'm thinking the way I'm adding the buttons won't allow me to implement what I am trying to accomplish. What do you guys think I'm doing wrong here?
Did you set scrollView.pagingEnabled to YES?

Resources