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
Related
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);
}
I am generating multiple buttons in my scrollview, A scroll view that has constrains at main.storyboard so it's width changes on different iphones. and i can't make my buttons to the center. Here is my code.
#synthesize table,scroll;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
img = #[#"Shirley-Stevens.jpg"];
NSUInteger i;
int buttonWidth=50;
int buttonHeight=50;
int space = 50;
// int xCoord= 100;// (scroll.frame.size.width/2) - buttonWidth - space;
// int Xcoord2= 200;//(scroll.frame.size.width/2) + buttonWidth + space;
int xCoord = (scroll.contentSize.width/2) + buttonWidth + space + buttonWidth + space;
int Xcoord2= (scroll.contentSize.width/2) + buttonWidth + space;
int yCoord=0;
int buffer = 10;
for (i = 1; i <= 100; i++)
{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:[img objectAtIndex:0]]forState:UIControlStateNormal];
aButton.frame = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
[aButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:aButton];
UIButton *bButton = [UIButton buttonWithType:UIButtonTypeCustom];
[bButton setBackgroundImage:[UIImage imageNamed:[img objectAtIndex:0]]forState:UIControlStateNormal];
bButton.frame = CGRectMake(Xcoord2, yCoord,buttonWidth,buttonHeight );
[bButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:bButton];
yCoord += buttonHeight + buffer;
}
[scroll setContentSize:CGSizeMake(300, yCoord)];
}
- (IBAction)whatever:(UIButton *)sender {
NSLog(#"Button");
}
Here is my Code Now that works fine, Basically the problem is, viewDidLoad called before the parameters of scrollview updates. So the best method to practice scrollview is viewDidAppear.
#synthesize table,scroll;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
img = #[#"Shirley-Stevens.jpg",
#"Shirley-Stevens.jpg"];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUInteger i;
int buttonWidth=50;
int buttonHeight=50;
int space = 50;
int xCoord = (scroll.frame.size.width/2) - buttonWidth - space;
int Xcoord2 = (scroll.frame.size.width/2) + space;
int yCoord=0;
int buffer = 10;
for (i = 1; i <= 100; i++)
{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:[img objectAtIndex:0]]forState:UIControlStateNormal];
aButton.frame = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
[aButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:aButton];
UIButton *bButton = [UIButton buttonWithType:UIButtonTypeCustom];
[bButton setBackgroundImage:[UIImage imageNamed:[img objectAtIndex:0]]forState:UIControlStateNormal];
bButton.frame = CGRectMake(Xcoord2, yCoord,buttonWidth,buttonHeight );
[bButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[scroll addSubview:bButton];
yCoord += buttonHeight + buffer;
}
[scroll setContentSize:CGSizeMake(300, yCoord)];
}
- (IBAction)whatever:(UIButton *)sender {
NSLog(#"Button");
}
I think you should make changes only below two line -
Assume that you need two button in center with space gap in between.
int xCoord = (scroll.contentSize.width/2) - (space/2) - buttonWidth;
int Xcoord2= (scroll.contentSize.width/2) + (space/2);
Hope this will help you.
Set the center point of UIButton along with frame.
For example: Set the center point at width/2 & height/2 of UIScrollView.
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.
I've got some buttons where I left align and line wrap the title text.
When I run the app, there is a delay from where the text is unformatted:
pre-format text http://imageshack.us/a/img28/1958/preformat.jpg
To when the alignment and wrapping take effect:
post-format text http://imageshack.us/a/img821/6118/postformat.jpg
On the simulator the delay is quite noticeable (~ 1 second), on my mate's iPhone 5 the delay is much smaller but still noticeable.
What causes this delay? Can I get around this delay?
Thanks in advance!
EDIT
In my viewDidLoad method I create 10 buttons:
for (int i = 1; i <= STEP_NUMBER; ++i)
[self createStepButtion:i isIphone:isIphone isRetina:isRetina];
In createStepButton, the relevant code is below:
UIButton * b = [UIButton buttonWithType:UIButtonTypeCustom];
// Listener
[b addTarget:self action:#selector(goToStep:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:b];
// Set button size.
CGFloat width = self.scrollView.frame.size.width;
// CGRectMake(x, y, width, height)
int y = stepNum * margin + (stepNum - 1) * buttonHeight;
int buttonWidth = width - margin * 2;
b.frame = CGRectMake(margin, y, buttonWidth, buttonHeight);
b.layer.cornerRadius = cornerRadius;
b.clipsToBounds = YES;
b.showsTouchWhenHighlighted = YES;
// Image
[b setImage:img forState:UIControlStateNormal];
b.imageEdgeInsets = [self makeImageInsets:buttonWidth];
// Text
[b setTitleEdgeInsets:UIEdgeInsetsMake(0, titleLeftMargin, 0, titleRightMargin)];
b.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
b.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
[b setTitle:[NSString stringWithFormat:#"%i - %s", stepNum, STEP_NAMES[stepNum - 1]]forState:UIControlStateNormal];
[b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
b.titleLabel.font = [UIFont systemFontOfSize:fontSize];
// Background
[b setBackgroundColor:[UIColor whiteColor]];
// The step number this button represents.
b.tag = stepNum;
I'm trying to add 16 UIButton in code to a subview of my main view:
internView = [[UIView alloc] initWithFrame:CGRectMake(16, 16, (self.view.frame.size.width - 16), (self.view.frame.size.height - 16) - 60)];
internView.backgroundColor = [UIColor whiteColor];
for (int rij = 0; rij < 4; rij++) //4 rows
{
for (int kolom = 0; kolom < 4; kolom++) //4 colomns
{
CGFloat x = (((width + spacing) * kolom) + spacing);
CGFloat y = (((height + spacing) * rij) + spacing);
int tag = ((4 * rij) + kolom);
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor blackColor];
[button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[projects objectAtIndex:tag]thumbnailImage]]]] forState:UIControlStateNormal];
[button addTarget:self action:#selector(getDetail:) forControlEvents:UIControlStateNormal];
button.tag = tag;
NSLog(#"%i",button.tag);
[internView addSubview:button];
}
}
[self.view addSubview:internView];
The subview 'internview' is visible (as i made it white background) on the main view but the buttons aren't visible.
Also my log shows the tag of the button which goes from 0..15, so I know they are being made but simple aren't added to the subview 'internview'
Can't really see what I'm missing or doing wrong here..
Change your code to :
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(x, y, width, height);
In your version you have:
Memory leak because you have created buttons two times
[UIButton buttonWithType:UIButtonTypeCustom]; returns new button
with CGRectZero frame