Adjusting button size in iPhone - iphone

I put a rounded-rect button into table-view footer.
But the button is streached to the left and to the right no matter how I change the BUTTON_WIDTH. But it's height is adjustable.
What's the problem? Below is the code I used.
#define BUTTON_WIDTH 80
#define BUTTON_HEIGHT 45
- (void)viewDidLoad {
CGRect frame = CGRectMake(0, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
// btnSeeResult is decleared in header file
btnSeeResult = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnSeeResult setTitle:#"Result" forState:UIControlStateNormal];
[btnSeeResult addTarget:self action:#selector(seeResult) forControlEvents:UIControlEventTouchUpInside];
btnSeeResult.frame = frame;
self.tableView.tableFooterView = btnSeeResult;
}

It's because you're setting the button to be the tableView.tableFooterView, so that view's width will always be set to the width of the tableView.
Try using a black UIView as the footer view then adding the button to it, like this:
#define BUTTON_WIDTH 80
#define BUTTON_HEIGHT 45
- (void)viewDidLoad {
CGRect frame = CGRectMake(0, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
// btnSeeResult is decleared in header file
UIButton *btnSeeResult = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnSeeResult setTitle:#"Result" forState:UIControlStateNormal];
[btnSeeResult addTarget:self action:#selector(seeResult) forControlEvents:UIControlEventTouchUpInside];
btnSeeResult.frame = frame;
// the width (320.0) actually doesn't matter here
UIView *footerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 80.0, 320.0)] autorelease];
footerView.backgroundColor = [UIColor clearColor];
[footerView addSubview:btnSeeResult];
self.tableView.tableFooterView = footerView;
}

#SeniorLee as per your question that you left in a comment-
The reason why it wasn't working when you were using the button as the footerview is because the footer view HAS to be the width of the table view. That is why when your button WAS your footerview, it was following the rule that it HAS to be the width of the table.
Now, when you use a regular old UIView, it takes the place of the footerview, and it's width is the same width as the table. Anything you add to that view, then, can be however you want it to be. Does that make sense?
The reason why the height could be changed is because the footerview's height doesn't have the same mandatory stipulations as the width does, so you can change the footer's height all you want, just not the width.

Related

Postioning UIImageSubview at center in UIScrollview

How to position the UIImageSubview at center in UIScrollview , I am Loading images dynalically in the uiscrollview so when i select any image in the Uiscrollview that Image should display at the center of screen in uiscrollview.
My Image Width is 65 and Screen width is 320 , I am facing problem setting the position of choosen image at the center of screen,
[scrollView1 setContentOffset:CGPointMake(130, 0) animated:YES];
scrollview just scroll to the 130 position. I don't want like this , I want the subview should be displayed at the center.
Please see the screenshot and tell me how to solve this problem.
How about
(pseudocode)
contentOffset.x = image.center.x - (screenwidth/2)
(expanded...)
UIImageView* imageView = //imageview that was selected
CGFloat screenWidth = 320;
CGPoint offset = scrollView1.contentOffset;
offset.x = imageView.center.x - screenWidth/2;
[scrollView1 setContentOffset:offset animated:YES];
I assume you already worked out how to get a pointer to the selected image...
(expanded further...)
Here is a fully-worked out version of the same, using buttons instead of images for ease of selection... try it (just copy into a new single-view project's viewContoller]), you will see that it works. If you are still having problems I expect it is the way you are identifying your image as the selected image for centering. You would need to update your question showing your code...
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = self.view.bounds;
frame.size.height = frame.size.height/2;
self.scrollView = [[UIScrollView alloc] initWithFrame:frame];
[self.view addSubview:self.scrollView];
[self.scrollView setContentSize:CGSizeMake(2000,self.scrollView.bounds.size.height)];
[self.scrollView setDelegate:self];
for (int i = 1; i < 20; i++) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString* title = [NSString stringWithFormat:#"button %d",i];
[button setTitle:title forState:UIControlStateNormal];
button.bounds = CGRectMake(0,0,80,60);
button.center = CGPointMake(i*100+50,self.scrollView.bounds.size.height/2);
[button addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
- (void)buttonPressed:(UIButton*)sender
{
CGFloat x = sender.center.x - self.scrollView.bounds.size.width/2.0f;
[self.scrollView setContentOffset:CGPointMake(x,0) animated:YES];
}

How to add View below other view in ViewController in iOS?

In my app i am creating view controller with mixed of UILabel and UITextview which want to be scrollable because the text are dynamic and also exceeds vertical screen size.
I am currently having Scrollview which has subviews as below. Views are created in Xcode 4.3 Storyboard.
UILabel1(Say Heading)
UITextView1(Dynamic text which can be any size)
UILabel2(Second Heading)
UITextView2(Dynamic text which can be any size)
and so on.
The problem is
When the UITextView1 has more content then it overlaps with UILabel2 which i don't want.
I would like to have UILabel1 on top of scrollView and UITextView1 below the UILabel1. UILabel2 below UITextView1 and so on.
What i have to do to achieve this?
EDIT
In Storyboard
![enter image description here][1]
In Simulator
![enter image description here][2]
Thanks for your help guys. Much appreciated.
Code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[scrollView setScrollEnabled:YES];
[self.view addSubview:cockTailNameLabel];
[self.view insertSubview:txtIngredients belowSubview:cockTailNameLabel];
[self.view insertSubview:scrollView belowSubview:cockTailNameLabel];
//[scrollView]
[self.cockTailNameLabel setText:self.passcockTailName];
[_txtUse setText:self.passUse];
[_txtUse setEditable:NO];
[_txtUse setUserInteractionEnabled:NO];
CGRect useFrame = _txtUse.frame;
useFrame.size.height = _txtUse.contentSize.height;
_txtUse.frame = useFrame;
[txtIngredients setText:self.passIngredients];
[txtIngredients setEditable:NO];
[txtIngredients setUserInteractionEnabled:NO];
CGRect ingredientFrame = txtIngredients.frame;
ingredientFrame.size.height = txtIngredients.contentSize.height;
txtIngredients.frame = ingredientFrame;
[txtRecipe setText:self.passReceipe];
[txtRecipe setEditable:NO];
[txtRecipe setUserInteractionEnabled:NO];
CGRect recipeFrame = txtIngredients.frame;
recipeFrame.size.height = txtRecipe.contentSize.height;
txtRecipe.frame = recipeFrame;
[scrollView insertSubview:_txtUse belowSubview:cockTailNameLabel];
[scrollView insertSubview:titleIngredients belowSubview:_txtUse];
[scrollView insertSubview:txtIngredients belowSubview:titleIngredients];
[scrollView insertSubview:btnReceipe belowSubview:txtIngredients];
[scrollView insertSubview:btnHome belowSubview:txtIngredients];
[scrollView insertSubview:txtRecipe belowSubview:btnHome];
[scrollView insertSubview:btnfacebookShare belowSubview:txtRecipe];
[scrollView insertSubview:btnTwitterShare belowSubview:txtRecipe];
/*[scrollView addSubview:_txtUse];
[scrollView addSubview:titleIngredients];
[scrollView addSubview:txtIngredients];
[scrollView addSubview:btnReceipe];
[scrollView addSubview:btnHome];
[scrollView addSubview:txtRecipe];
[scrollView addSubview:btnfacebookShare];
[scrollView addSubview:btnTwitterShare];*/
[scrollView setContentSize:CGSizeMake(320, 1000)];
NSLog(#"RecipeName :%# ",passcockTailName);
}
In Storyboard or IB you can rearrange them freely.
In code you do - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview.
In code (in viewDidLoad):
UIScrollView *scroll =[[UIScrollView alloc] initWithFrame:CGrectMake(0,0 320, 480)];
[self.view addSubview:scroll];
// code to init your UI object
UILabel *uilabel1 = [[UIlabel alloc] initWithFrame:CGrectMake(10,10, 100, 40)]; // example
uilabel1.font = [UIFont systemFontOfSize:10];
uilabel1.text = #"UILabel1";
uilabel1.backgroundColor = [UIColor clearColor];
//
//
UILabel *uilabel2 = [[UIlabel alloc] initWithFrame:CGrectMake(10, 10 + 10 + uilabel1.frame.origin.y, 100, 40)]; // example
uilabel2.font = [UIFont systemFontOfSize:10];
uilabel2.text = #"UILabel2";
uilabel2.backgroundColor = [UIColor clearColor];
//
//
[scroll addSubview:uilabel1];
[uilabel1 releale];
[scroll addSubview:uilabel2];
[uilabel2 releale];
//
//
// in end
float offset = 10.0 * 2; // offset between uiobjects, N - number of objects
scroll.contentSize = CGSizeMake (0, 0, uilabel1.frame.size.height + uilabel2.frame.size.height + offset, 320);
Note that you may set frame (and other properties) of yours uiobjects and adds it in order to descend.
You can tell next view to start from the end of the first view like so:
startYOfNextView = firstView.frame.origin.y position + firstView.frame.size.height;
Do the same for the rest of the other view. If your view has variable text length, you may need to precaculate the height of the string based on a specific font e.g.:
CGSize maxSize = CGSizeMake(widthOfView, 9999999);
CGSize expectedSize = CGSizeMake(stringVar sizeWithFont:[UIFont fontWithName:#"Arial"] withMaxSize:maxSize lineBreakMode:UILineBreakModeWordWrap);
then tell your dynamic view to use the height of expectedSize variable like so:
myDynamicView = [[UILabel alloc] initWithFrame:CGRectMake(..., expectedSize.height)];
Your issue is labels are coming on top of the textview (Overlapped), right?
In This case, you are modifying the height of the textview dynamically. If its just for display purpose you can set the text to a UILabel with numberOfLines = 0 instead of UITextview; As its added to scrollview adding a label will be fine.
Also you need to modify the origin.y of the remaining views so that it will be properly aligned. ie, secondView.origin.y = firstView.origin.y + firstView.size.height + offset. Likewise modify the origin of the remaining views wrt the just above view. So that its origin will lie outside the previous view frame.
In my case I had to project it over the parent view, so remember there is also something,
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview
I think adding a transparent UI button is the fastest solution. You could add it once and then show / hide whenever you need to disable all views below the current one (assuming the "current" view, say a popup, was added last to your superview).
Declare an instance variable UIButton* _parentDisablingOverlay; in your popup view, then add this in its init or layoutSubviews method:
_parentDisablingOverlay = [[UIButton alloc] initWithFrame:CGRectMake(0,0, self.superview.frame.size.width, self.superview.frame.size.height)];
[self.superview insertSubview:_parentDisablingOverlay belowSubview:self];
_parentDisablingOverlay.hidden = true;
Later on, when you want to show the popup and disable everything below:
- (void) open {
self.hidden = false;
_parentDisablingOverlay.hidden = false;
}
Similarly to close and re-enable everything:
- (void) close {
self.hidden = true;
_parentDisablingOverlay.hidden = true;
}

Setting the position of setImage and setTitle of UIButton

I want to have a large button the spans the length of my table cells that contains a setImage icon on the right and a setTitle on the left. However, what happens by default is that everything is aligned to the left.
Is there a way to change the position of the UIButton image and title views? I want everything to be in one button so that if someone clicks the title the icon will change its state as well.
Make your image the same size as the button (i.e. pad it out with transparency) so things go where you want them to be. Say you have an image that 40 x 40, but you want it on the right side of a button 300 x 40. Just increase the size of the image with transparency to have 260 pixels of nothing on the left. For your text, you can use the alignment icons in Interface builder to put the title where you want it.
What I did was subclass UIButton and set [self titleLabel] and [self imageView] in the layoutSubview method.
#import "CustomDetailTableButton.h"
#implementation CustomDetailTableButton
- (void)layoutSubviews
{
[super layoutSubviews];
UILabel *titleLabel = [self titleLabel];
CGRect fr = [titleLabel frame];
fr.origin.x = 10.0;
fr.origin.y = 5.0;
[[self titleLabel] setFrame:fr];
UIImageView *imageView = [self imageView];
CGRect iFrame = [imageView frame];
iFrame.origin.x = 300.0;
iFrame.origin.y = 7.0;
[[self imageView] setFrame:iFrame];
}
#end

How to create a round button?

I want to create a round circular button. This button should look like a circle.
This code gives round rectangular button.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 100, 100, 30);
UIImage *image = [UIImage imageNamed:#"01.png"];
[button setImage:image forState:UIControlStateNormal];
[image release];
I figured out how to create a rounded rectangular button but I want to create a round circle button. What do I need to change?
Tested Code:
.h
#import <QuartzCore/QuartzCore.h>
-(void)roundButtonDidTap:(UIButton*)tappedButton;
.m
#define ROUND_BUTTON_WIDTH_HEIGHT YourButtonWidthToBeSetHere
-(void)roundButtonDidTap:(UIButton*)tappedButton{
NSLog(#"roundButtonDidTap Method Called");
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"TimoonPumba.png"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(roundButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
//width and height should be same value
button.frame = CGRectMake(0, 0, ROUND_BUTTON_WIDTH_HEIGHT, ROUND_BUTTON_WIDTH_HEIGHT);
//Clip/Clear the other pieces whichever outside the rounded corner
button.clipsToBounds = YES;
//half of the width
button.layer.cornerRadius = ROUND_BUTTON_WIDTH_HEIGHT/2.0f;
button.layer.borderColor=[UIColor redColor].CGColor;
button.layer.borderWidth=2.0f;
[self.view addSubview:button];
Result
Geometry in this concept
Storyboard Option (should apply to Swift or ObjC) -
If you prefer to work in Storyboards, there's another option.
First, set the width and height to be the same value to make a perfect square.
Second, type in the following attributes. IMPORTANT- make the value of your layer.cornerRadius half the size of your width.
Then, when you run the app, your button will be round.
Try this, it worked for me. It will make your button or any view in circular shape only if you have taken it in square i.e width should be equals to height.
yourButton.layer.cornerRadius = yourButton.bounds.size.width/2;
In Xcode 7.0.0 on IOS 8 this code works perfectly for me.
Provided the length and height of button frame is same.
myButton.clipsToBounds = YES;
myButton.layer.cornerRadius = myButton.layer.frame.size.width/2;
UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(50,50,30,30);
[myButton addTarget:self action:#selector(buttonEvent) forControlEvents:UIControlEventTouchUpInside];
[myButton setImage:[UIImage imageNamed:#"sarabjit.png"] forState:UIControlStateNormal];
[self.view addSubView:myButton];
Using Swift like the answer of
Vijay-Apple-Dev.blogspot :
let ROUND_BUTTON_WIDTH_HEIGHT YourButtonWidthToBeSetHere
override func viewDidLoad() {
super.viewDidLoad()
var button = UIButton.buttonWithType(.Custom) as UIButton
button.frame = CGRectMake(160, 100, ROUND_BUTTON_WIDTH_HEIGHT, ROUND_BUTTON_WIDTH_HEIGHT)
button.layer.cornerRadius = ROUND_BUTTON_WIDTH_HEIGHT / 2.0
button.layer.borderColor = UIColor.redColor().CGColor
button.layer.borderWidth = 2.0
button.setImage(UIImage(named:"TimoonPumba.png"), forState: .Normal)
button.addTarget(self, action: "roundButtonDidTap", forControlEvents: .TouchUpInside)
button.clipsToBounds = true
view.addSubview(button)
}
func roundButtonDidTap() {
NSLog(#"roundButtonDidTap Method Called");
}
override func viewDidLoad() {
super.viewDidLoad()
let facebookButton = UIButton()
facebookButton.frame = CGRectMake(30, 200, 150, 150)
facebookButton.layer.cornerRadius = 75
facebookButton.layer.masksToBounds = true
self.view.addSubview(facebookButton)
}
** To make round button you have to give same height and same width for the button and half of the value should be given to corner radius **
Step 1. Use [UIButton buttonWithType:UIButtonTypeCustom] to create the button.
Step 2. CGRectMake(100, 100, 100, 30) is a rectangular shape. Maybe you want to use the size of your image instead, like this:
CGRect frame = CGRectMake(100, 100, 0, 0);
frame.size = img.size;
button.frame = frame;
a round-rect button with circular image does not satisfy the need of a round Button. Nor even if they are made custom buttons. This is because, This buttons will respond to taps even outside the circular part ( which is a just a .png image ) if it is inside the button size range and not clipped.
The first answer(and only the first one by #vijay-apple-dev) given here is correct. You need to clip the boundary of the button frame in order to stop it responding just outside the image
make a
[UIButton buttonWithType:UIButtonTypeCustom];
and try to use the corner radius property
button.layer.cornerRadius = button.bounds.size.width/2 / 2.0

Dynamic Button Layout without hard coding positions

I would like to implement a view (it will actually be going into the footer of a UITableView) that implements 1-3 buttons. I would like the layout of these buttons (and the size of the buttons themselves) to change depending on which ones are showing. An example of almost the exact behavior I would want is at the bottom of the Info screen in the Contacts application when you are looking at a specific contact ("Add to Favorites" disappears when it is clicked, and the other buttons expand to take up the available space in a nice animation).
As I'm running through the different layout scenarios, I'm hard coding all these values and I just think... "this is NOT the way I'm supposed to be doing this."
It even APPEARS that Interface Builder has some features that may do this for me in the ruler tab, but I'll be darned if I can figure out how they work (if they work) on the phone.
Does anyone have any suggestions, or a tutorial online that I could look at to point me in the right direction?
Thanks much.
You could take a look at
Stanford cs193p classes
I think there is a demo in one of the lessons/example where they programaticaly set the autoresize of the buttons and some other where they animate the view.
you can also make the view set dynamically the width of each of its subview to (ownWidth/numberofSubView),the same for the positon of each elements.
[edit] like that ? it's not "dynamic" yet, but you've got the idea
you can increase/decrease numberOfbuttons when "adding/removing" a button then reset the new frame of all the subviews
- (void)loadView
{
UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
view.backgroundColor = [UIColor lightGrayColor];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
int numberOfbuttons = 2;
CGFloat buttonsLegth = (-20+view.bounds.size.width)/numberOfbuttons-20;
for(int i=0;i<numberOfbuttons;i++){
CGRect buttonFrame = CGRectMake(0, 0, buttonsLegth, 37);
buttonFrame.origin.x = (buttonFrame.size.width+20)*i + 20.0;
buttonFrame.origin.y = 20.0;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // Autoreleased
button.frame = buttonFrame;
[button setTitle:#"Done" forState:UIControlStateNormal];
[view addSubview:button];
}
self.view = view;
[view release];
}
hi remove all buttons in view and add again using this method...
you have to pass number of buttons and a UIView in which you want to add these buttons
-(void)addButtons:(int)numberOfButtons ToView:(UIView *)containerView;
{
CGRect containerRect = containerView.frame;
CGFloat padding = 5.0;
CGFloat width = (containerRect.size.width - (padding*numberOfButtons+1))/numberOfButtons;
for (int i = 1; i<=numberOfButtons; i++)
{
UIButton * btn = [[[UIButton alloc] initWithFrame:CGRectMake(i*padding+width, 0, width, containerRect.size.height)]autorelease];
//set Button Properties like Target,backColor,Title,,,,etc MUST SET TAG TO ACCESS THEM IN CLICK METHOD IF YOU ARE USING SAME SELECTOR FOR ALL BUTTONS.
[containerView addSubview:btn];
}
}
Try this and have fun......