How could I make this work with UIScrollView? - ios

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?

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);
}

Dynamic generate buttons

I want to dynamic generate a few buttons, the number will be given by background. When I get it, I must use it to create the corresponding number buttons,each button will be the same size and the space between them are the same, if the button can not contain in a row, it will line feed. The minimum width will be a constant,but the actual length will be according title text of the button.
My code is below, but it can't line feed, also I don't know how to use the text to determine the length of the button, grateful for any guidance.
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat testHeight = 50;
CGFloat testWidth = 100;
CGFloat spaceing = 10;
int number = 5;
for (int i = 0; i < number; i++) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(spaceing + testWidth * i + spaceing * i , 100 , testWidth, testHeight )];
[button setBackgroundColor:[UIColor redColor]];
[self.view addSubview:button];
}
}
You could use a UICollectionView to do this, but it is not difficult to implement just using an array of UIButtons. You can use sizeToFit to have the button size itself based on its title. To get your buttons to wrap you should just check if it will extend past the max x of the view you are adding them to, in your case self.view.
For example you could say something like:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *buttonStrings = #[#"how", #"now", #"brown", #"cow", #"the", #"quick", #"brown", #"fox"];
NSMutableArray *buttons = [[NSMutableArray alloc]initWithCapacity:[buttonStrings count]];
for (NSString *string in buttonStrings)
{
UIButton *button = [self buttonForString:string];
[buttons addObject:button];
}
[self layoutButtonArray:buttons inView: self.view];
}
// takes an array of buttons and adds them as subviews of view
- (void)layoutButtonArray:(NSArray<UIButton *> *)buttons inView:(UIView *)view
{
CGFloat spacing = 10.0;
CGFloat xOffset = spacing;
CGFloat yOffset = spacing;
for (UIButton *button in buttons)
{
if((xOffset + button.bounds.size.width + spacing) > CGRectGetMaxX(view.bounds))
{
xOffset = spacing;
yOffset += (button.bounds.size.height + spacing);
}
button.frame = CGRectMake(xOffset, yOffset, button.bounds.size.width, button.bounds.size.height);
[view addSubview:button];
xOffset += (button.bounds.size.width + spacing);
}
}
// Takes a string returns a button sized to fit
- (UIButton *) buttonForString:(NSString *)string
{
UIButton *button = [[UIButton alloc]initWithFrame:CGRectZero];
button.backgroundColor = [UIColor redColor];
[button setTitle:string forState:UIControlStateNormal];
[button sizeToFit];
// if you want to have a minimum width you can add that here
button.frame = CGRectMake(button.frame.origin.x, button.frame.origin.y, MAX(button.frame.size.width, kMinWidth), button.frame.size.height);
return button;
}

UIScrollView needs to get bigger every time I add a button

The scrollView is created in my storyboard and is horizontal. Here is the method where I add a button for every loop and need to increase the size of the scrollView every time a button is added.
- (void) populateGroups {
NSInteger x = [self.groupNameArray count];
for (int i = 0; i < x; i++) {
NSString *name = [self.groupNameArray objectAtIndex:i];
// Create Button
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(count, 0, 100, 54)];
[button setTitle:name forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:10];
[button.layer setBorderWidth:1.0f];
[button.layer setBorderColor:[UIColor whiteColor].CGColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(groupPage:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.groupScrollView addSubview:button];
count = count + 100;
// Increase ScrollViewSize
self.groupScrollView.frame = CGRectMake(0, 0, frameWidth, 80);
frameWidth = frameWidth + 100;
}
}
The scrollView stays the same when I try to add two buttons to the view.
you have to increase the content size of the scroll view like:
self.groupScrollView.contentSize = CGSizeMake(frameWidth, 80);
and better to do it after the loop.

Adding an array of buttons to a particular subview

I have a subview that is hidden until a user clicks a button (The subview is a UIScrollview). I'd like to programmatically add a grid of buttons in that view. I'm not sure how to specify which view the buttons get added to. I'm trying to follow http://www.raywenderlich.com/130/how-to-write-a-custom-image-picker-like-uiimagepicker
the scrollview is called graphicView
This is what I have
for(int i=0;i<64;i++)
{
UIImage *buttonImage=[UIImage imageNamed:#"image.png"];
[arrayOfThumbnails addObject:buttonImage];
}
for(int i = 0; i < arrayOfThumbnails.count; ++i) {
UIImage *thumb = [arrayOfThumbnails objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+24, row*80+10, 64, 64);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:graphicView
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[graphicView addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
This is the only part I'm not using from the tutorial....
[view setContentSize:CGSizeMake(320, (row+1) * 80 + 10)]; self.view
= view;
Make sure the UIImage is valid by checking the return value from [UIImage imageNamed:#"image.png"]
Check that your NSMutableArray has been initialized
Your for loop looks unusual, try changing to fast enumeration
for (UIImage *thumb in arrayOfThumbnails) {
// UIImage *thumb = [arrayOfThumbnails objectAtIndex:i]; <-- Not needed
...
}
Is graphicView being added as a subview somewhere? Set graphicView.backgroundColor = [UIColor redColor] so you can see at least it's being added.

text not visible after moving UIButtons

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.

Resources