Programmatically Click 10 UIButtons one after another in UIScrollView - ios

I am developing one control where 10 UIButtons are added in UIScrollView. Now I have a requirement to click every Button one after another after some delay. can you all guide me how to do that?
here is the code what I have done.
in viewcontroller.h file
#property (weak) IBOutlet UIScrollView *mapScrollView;
#property (strong) UIButton *addContactIcon;
in viewcontroller.m file
// Set up ScrollView with UIButtons
NSUInteger xPosition = 1;
NSUInteger countIndex = 0;
for (ContactModule *sortedContacts in _distanceList) {
_addContactIcon = [[UIButton alloc] initWithFrame:CGRectMake(xPosition, 7, 30, 30)];
_addContactIcon.tag = countIndex;
[_addContactIcon addTarget:self action:#selector(mapsScrollButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
_addContactIcon.layer.cornerRadius = 2.0;
_addContactIcon.clipsToBounds = YES;
[_addContactIcon setBackgroundImage:[UIImage imageWithContentsOfFile:dataPath] forState:UIControlStateNormal];
[_addContactIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_mapScrollView addSubview:_addContactIcon];
xPosition += _addContactIcon.frame.size.width + 2;
countIndex = countIndex + 1;
}
_mapScrollView.contentSize = CGSizeMake(30 * _distanceList.count + 34, 40);
[_mapScrollView setShowsHorizontalScrollIndicator:NO];
Here is the Button Click Method For Every Button:
- (void)mapsScrollButtonClicked:(UIButton *)clickButton {
// Set Annotation Callout
[_mapsView selectAnnotation:[_mapsView.annotations objectAtIndex:clickButton.tag] animated:YES];
}
Now the requirement is I want to call Action Method for Every UIButtons in UIScrollview. for that I am doing something wrong below. help me with that:
for(NSUInteger count=0; count<[_distanceList count];count++) {
[UIView animateWithDuration:0.4
delay:0.8
options:0
animations:^{
[_addContactIcon sendActionsForControlEvents:UIControlEventTouchUpInside];
} completion:nil];
}

Hi you could do soemthing like below to click all the UIButtons on your view.
UIButton *button;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *buttonMaster;
buttonMaster = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonMaster addTarget:self
action:#selector(masterButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
[buttonMaster setTitle:#"Show View" forState:UIControlStateNormal];
buttonMaster.frame = CGRectMake(80.0, y, 160.0, 40.0);
buttonMaster.tag = 100;
[self.view addSubview:buttonMaster];
y = 60;
for (int x=0; x<=10; x++)
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(button1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, y, 160.0, 30.0);
button.tag = x;
//[paintView addSubview:button];
[self.view addSubview:button];
y = y + 70;
}
[buttonMaster sendActionsForControlEvents:UIControlEventTouchUpInside];
if ([[self.view viewWithTag:0] isKindOfClass:[UIButton class]]) {
//UIButton *button = (UIButton *) view;
// do something funky with button
UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
NSLog(#" button tapped is %ld", myBtns.tag);
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
[myBtns setBackgroundColor:[UIColor greenColor]];
} else {
// do something funky with view
NSLog(#"do nothing ");
}
}
- (void)listSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
// Return if there are no subviews
//if ([subviews count] == 0) return; // COUNT CHECK LINE
for (UIView *subview in subviews) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:subview.tag];
//UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
if(myBtns.tag == 100 ){
NSLog(#"Master Button tag :- Dont do anything ");
}else
{
//[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
NSLog(#"tags are %ld ", myBtns.tag);
}
// List the subviews of subview
//[self listSubviewsOfView:subview];
}
}
-(void) clickAllButtons{
for (int i = 0; i<=10; i++) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:i];
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
}
}
- (IBAction)masterButtonTapped:(UIButton*)sender{
//[self listSubviewsOfView:self.view];
// [self clickAllButtons];
}
- (IBAction)button1:(UIButton*)sender{
NSLog(#"test");
//NSLog(#"Button clicked %ld", tag);
}

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

how to make UIView work as an scrollview

I need some serious help on this problem of mine where I need to work a UIView as an ScrollView. Below uploaded picture will clear all the doubts.
I have taken four buttons along with a UIView below them along with 4 container views which I have placed one above the other so as to work along with the four buttons.. What I want now is to work UIView as an ScrollView. Whenever I click any button, the View moves forward as well as the it changes the container view. And respective container view shows whenever I click a button.
Hi better you can use UIScrollView instead of UIView like:
//Declare it
NSMutableArray * buttonArray
int selectedIndex;
-(void)setUpSegmentBar {
NSArray * namesOfMenus =#[#"Button1",#"Button2",#"Button3",#"Button4",#"Button5"];
// Scrollview added on storyBoard
myScrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 2, self.view.frame.size.width, 40)];
CGFloat scrollWidth = 0.f;
buttonArray=[[NSMutableArray alloc]init];
for ( int j=0; j<namesOfMenus.count; j++)
{
NSString * name =[namesOfMenus objectAtIndex:j];
CGSize size = [name sizeWithAttributes:
#{NSFontAttributeName: [UIFont fontWithName:font_bold size:font_size_button]}];
CGSize textSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
CGFloat strikeWidth;
if (iPAD) {
strikeWidth = self.view.frame.size.width/5.5;
}else{
strikeWidth = textSize.width;
}
CGRect frame = CGRectMake(scrollWidth, 0,strikeWidth+20, 40);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:j];
button.frame = frame;
[button setBackgroundColor:[UIColor whiteColor]];
button.titleLabel.textColor=[UIColor whiteColor];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.layer.borderColor=[UIColor whiteColor].CGColor;
button.titleLabel.textAlignment=NSTextAlignmentCenter;
[button addTarget:self action:#selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:name forState:UIControlStateNormal];
// ScrollWidth As per Button Width
scrollWidth= scrollWidth+strikeWidth+20;
// to Check Which Button Is Selected.
if (j==selectedIndex) {
// If Selected Do UI Changes
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
// Other Buttons
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_disselected_Color;
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
// Add Buttons in Array
[buttonArray addObject:button];
// Add button on Scroll View
[myScrollView addSubview:button];
}
myScrollView.contentSize = CGSizeMake(scrollWidth, 30.f);
myScrollView.pagingEnabled = NO;
myScrollView.backgroundColor=[UIColor whiteColor];
[myScrollView setShowsHorizontalScrollIndicator:NO];
[myScrollView setShowsVerticalScrollIndicator:NO];
return myScrollView;
}
And For Handeling button action.
-(void)buttonEvent:(UIButton*)sender
{
NSInteger index= sender.tag;
selectedIndex= (int) index;
for(int i=0;i<buttonArray.count;i++)
{
UIButton * button =(UIButton*)[buttonArray objectAtIndex:i];
if (i==selectedIndex) {
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
button.backgroundColor=segment_selected_Color ;
[button setTitleColor:segment_disselected_Color forState:UIControlStateNormal];
[button addShaddow];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}else {
button.backgroundColor=segment_disselected_Color;
[button addLayerAndCornerRadius:0 AndWidth:1 AndColor:segment_disselected_Color];
[button setTitleColor:segment_selected_Color forState:UIControlStateNormal];
if (iPhone6||iPhone6plus) {
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}else{
button.titleLabel.font=[UIFont fontWithName:font_bold size:font_size_normal_regular];
}
}
}
CGRect frame1 = myScrollView.frame;
UIButton * bt=(UIButton*)[buttonArray objectAtIndex:index];
frame1 =bt.frame ;
// By using it button will scroll and show properly
[myScrollView scrollRectToVisible:frame1 animated:YES];
[self setupTableAfterClick];
}

How to make segmented control like this

Today I'm creating a custom segmented control. The appearance of the control as follow:
I tried two methods:
- (void)setBackgroundImage:(UIImage *)backgroundImage
forState:(UIControlState)state
barMetrics:(UIBarMetrics)barMetrics
- (void)setDividerImage:(UIImage *)dividerImage
forLeftSegmentState:(UIControlState)leftState
rightSegmentState:(UIControlState)rightState
barMetrics:(UIBarMetrics)barMetrics
However, here is the result I got:
I extracted the border image and the divider line (vertical line) from the design, but the result looks bad. Please help me if you have any idea.
I have always found it too much work to customize the UISegmentedControl and it is not really fully customizable.
I suggest you create yourself a custom UIView inheriting 3 buttons. They are fully customizable and fully controllable:
#define BASE_TAG 123
NSArray *titles = [NSArray arrayWithObjects:#"MAP", #"LOCATIONS", #"BUS", nil];
double y = 0.0;
double x = 0.0;
double width = (frame.size.width / [titles count]);
double height = frame.size.height;
for (int i = 0; i < [titles count]; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button setBackgroundColor:[UIColor clearColor]];
[button setTag:(BASE_TAG + ([titles count] - i - 1))];
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[_buttons addObject:button];
x += width;
}
This is your button action. Here the button clicked will be selected and all others unselected:
- (void)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
NSInteger index = 0;
for (UIButton *btn in self.subviews)
{
if (btn == button)
{
index = (btn.tag - BASE_TAG);
[btn setBackgroundColor:[UIColor colorFromHexString:#"#5ac8f5" alpha:1.0]];
[btn setSelected:YES];
}
else
{
[btn setBackgroundColor:[UIColor clearColor]];
[btn setSelected:NO];
}
}
/* Trigger a delegate here if you like
if ([_delegate respondsToSelector:#selector(didSelectedIndex:)])
{
[_delegate didSelectedIndex:index];
}
*/
}
This lets you pre set a selected index:
- (void)setSelectedIndex:(NSInteger)index
{
for (UIButton *button in self.subviews)
{
if (button.tag == (BASE_TAG + index))
{
[button setBackgroundColor:[UIColor colorFromHexString:#"#5ac8f5" alpha:1.0]];
[button setSelected:YES];
}
else
{
[button setBackgroundColor:[UIColor clearColor]];
[button setSelected:NO];
}
}
}
This is just a suggestion code I pulled from an old project. You will have to customize it for your needs.
Here is a very good article how to do custom segmented control.
Looks like you have tried similar approach but you have messed up something with images (probably you misunderstand the API so this article should do the job for you).

How to remove the button pragmatically with tag

I am adding button subView to each row I click. I am trying to remove the button subView every time once I click on different row and add button subview to the other row I click.
Where would be my issue? It is adding subView to each row without removing any of them.
if (sender.tag == 212)
{
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//Debug shows that every-time myButton&myButton2 hasn't tag??
if (myButton2.tag != 0 && myButton.tag != 0)
{
[myButton removeFromSuperview];
[myButton2 removeFromSuperview];
}
UITableViewCell *cell = (id)sender.superview.superview.superview;
CGPoint center= sender.center;
CGPoint rootViewPoint = [sender.superview convertPoint:center toView:commonTable.table];
NSIndexPath *indexPath1 = [commonTable.table indexPathForRowAtPoint:rootViewPoint];
itemdata1 = [itemList objectAtIndex:indexPath1.row];
if (closeManager) [closeManager release];
CGFloat __y = commonTable.y + commonTable.table.y - commonTable.table.contentOffset.y + cell.height*indexPath1.row + sender.y;
CGFloat __x = commonTable.x + commonTable.table.x + sender.x;
CGRect layerBox1 = CGRectMake(618, __y, 90, sender.height+3);
CGRect layerBox2 = CGRectMake(888, __y, 94, sender.height+3);
NSLog(#"%f and %f", __x, __y);
myButton.frame = layerBox1;
[[myButton layer] setBorderWidth:2.0f];
myButton.layer.borderColor = [UIColor redColor].CGColor;
[myButton addTarget:self action:#selector(func1:) forControlEvents:UIControlEventTouchUpInside];
myButton2.frame = layerBox2;
[[myButton2 layer] setBorderWidth:2.0f];
[myButton2 addTarget:self action:#selector(func2:) forControlEvents:UIControlEventTouchUpInside];
myButton2.layer.borderColor = [UIColor redColor].CGColor;
[self addSubview:myButton];
[self addSubview:myButton2];
myButton.tag = myButton2.tag = 666;
}
Edited for Bhumeshwer katre:
if (myButton&&myButton2)
{
[myButton removeFromSuperview];
[myButton2 removeFromSuperview];
}
//Other variables
if(!myButton){
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = layerBox1;
[[myButton layer] setBorderWidth:2.0f];
myButton.layer.borderColor = [UIColor redColor].CGColor;
[myButton addTarget:self action:#selector(func1:) forControlEvents:UIControlEventTouchUpInside];
myButton.tag = 666;
[self addSubview:myButton];
}
don't create each time your button like this
Here you are creating each time new instance of UIButton
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
And you are doing this
//Debug shows that every-time myButton&myButton2 hasn't tag??
if (myButton2.tag != 0 && myButton.tag != 0)
{
[myButton removeFromSuperview];
[myButton2 removeFromSuperview];
}
//It will just remove new instance of UIButton and no more your UIButton will be there on UIView.
try like this
if(!myButton){
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}
if(!myButton2) {
myButton2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}
//Don't remove your button just change frame
if you still want to remove buttons then first remove
[myButton removeFromSuperview];
[myButton2 removeFromSuperview];
//then create new instance of button
Try adding tags to buttons before adding them to subview.
So this:
[self addSubview:myButton];
[self addSubview:myButton2];
myButton.tag = myButton2.tag = 666;
should become like this:
myButton.tag = myButton2.tag = 666;
[self addSubview:myButton];
[self addSubview:myButton2];
Regards,
hris.to
If you use tableview cell, Use this following cases,
1) Set tag to button while creating tableViewCell.
2) Hide that button by cell.yourButton.hidden = YES
3) When you click on row, just note down that indexPath as self.selectedIndexPath = indexPath in didSelectRowAtIndexPath:
4) Now reload your tableView. Just add one condition in cellForRowAtIndexpath: as below.
if (indexPath.row == self.selectedIndexPath.row)
{
cell.yourButton.hidden = NO;
}
else
cell.yourButton.hidden = YES;
for (UIView *view in self.view.subView) { // instead of self.view you can use your main view
if ([view isKindOfClass:[UIButton class]] && view.tag == ?) {
UIButton *btn = (UIButton *)view;
[btn removeFromSuperview];
}
}
i think you have to set tag your buttons first,because default tag of every UIControl is 0;

UIScrollView with a large number of UIButtons

What I want is a UIView with lots of UIButtons in it. They get placed and arranged according to data stored in an NSArray. Because there are quite a lot of buttons they don't fit on the screen all at once. The user should be able to zoom out to see all the buttons or to zoom in to see details (the label on them) and to easily select them.
I tried two different approaches:
1) I constructed a UIView subclass, put the buttons in it and an instance of this View inside a UIScrollview.
Effect: I can access all Buttons via their tag and scrolling and zooming works fine. BUT I can't get the buttons to handle any events (press on them)...
2) I wrote a UIViewController with exactly the same functionality and added an instance of it to the UIScrollView.
Effect: I can press the buttons now, but scrolling and zooming have stopped to work.
Here the relevant Code of the View:
- (UIView *)initWithArray:(NSArray *)nArray{
self = [super init];
if (self) {
int count = [nArray count];
for (int i=0; i<count; i++) {
UIButton *button = [[UIButton alloc]
initWithFrame:(__some Code to place the Button__);
button.tag = i+1;
NSString *title = [[NSString alloc] initWithFormat:__code for generating Title__];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[self addSubview:button];
}
}
return self;
}
And the Code for the matrixController:
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *nArray = [[NSMutableArray alloc] __some code___];
int count = [nArray count];
for (int i=0; i<count; i++) {
UIButton *button = [[UIButton alloc]
initWithFrame:CGRectMake(__some Code to place the Button__];
button.tag = i+1;
NSString *title = [[NSString alloc] initWithFormat:__code for generating Title__];
[button setTitle:title forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:14];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button];
}
}
And the code for the ScrollViewController:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 768, 970)];
[self.view addSubview:scrollView];
[scrollView setBackgroundColor:[UIColor blackColor]];
//Zooming
[scrollView setMinimumZoomScale:0.25];
[scrollView setMaximumZoomScale:4.0];
[scrollView setDelegate:self];
// constructing the view
[scrollView addSubview:chartView];
[scrollView bringSubviewToFront:chartView];
OR
[scrollView addSubview:[matrixController view]];
How can I get this to work??
I'm able to get a scroll view containing multiple buttons to pan and zoom just fine, with the buttons still handling touch events:
- (void)didTapButton:(UIButton *)button
{
NSLog(#"Button %ld", (long)button.tag);
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scrollView.delegate = self;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3.0f, scrollView.frame.size.height * 3.0f);
scrollView.maximumZoomScale = 3.0f;
UIView *zoomView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, scrollView.contentSize.width, scrollView.contentSize.height)];
zoomView.backgroundColor = [UIColor whiteColor];
for (NSInteger index = 0; index < 100; index++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 50.0f, 10.0f + (50.0f * (CGFloat)index), 100.0f, 30.0f);
button.tag = index;
[button setTitle:[NSString stringWithFormat:#"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
[button addTarget:self action:#selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
[zoomView addSubview:button];
}
[scrollView addSubview:zoomView];
[self.view addSubview:scrollView];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView.subviews objectAtIndex:0];
}
EDIT: I said not to rely on tag in my comment below, yet I'm doing in here. :) It's merely so I could log the button number, so that part should be ignored.
for (int i=0; i<10; i++)
{
UIButton *scrollingbutton_outlet = [[UIButton alloc] init];
scrollingbutton_outlet = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:#"box_normal.png"];
scrollingbutton_outlet.frame = CGRectMake(0, 100, img.size.width, img.size.height);
[scrollingbutton_outlet setTitle:[NSString stringWithFormat:#"%d",i+1] forState: UIControlStateNormal];
scrollingbutton_outlet.tag=i+1;
[buttonArray addObject:[NSString stringWithFormat:#"%d",i+1]];
buttonArray = [[NSMutableArray alloc] init];
[scrollingbutton_outlet setBackgroundImage:img forState:UIControlStateNormal];
[scrollingbutton_outlet addTarget:self
action:#selector(scrollbuttonpress:)
forControlEvents:UIControlEventTouchUpInside];
scrollingbutton_outlet.frame = CGRectMake(img.size.width*i,0, img.size.width, scrollviewoutlet.frame.size.height);
[scrollviewoutlet addSubview:scrollingbutton_outlet];
width = scrollingbutton_outlet.frame.size.width;
height = scrollingbutton_outlet.frame.size.height;
scrollviewoutlet.contentSize = CGSizeMake(width*i+scrollingbutton_outlet.bounds.size.width+5, height);
}

Resources