Understanding the Aspect ratio constraint and multiplier - ios

I have created a UIScrollview programmatically. And I have added some programmatically created buttons onto this scroll view. Button height is 30. But the button width changing according to the screen size.
float scrollYearX=btnLeftArrow.frame.origin.x+btnLeftArrow.frame.size.width+15;
float scrollYearY=40.0;
float scrollYearWidth=btnRightArrow.frame.origin.x-15-scrollYearX;
float scrollYearHeight=50.0;
scrollYear=[[UIScrollView alloc] initWithFrame:CGRectMake(scrollYearX, scrollYearY, scrollYearWidth, scrollYearHeight)];
[scrollYear setShowsHorizontalScrollIndicator:NO];
[scrollYear setShowsVerticalScrollIndicator:NO];
[vwParent addSubview:scrollYear];
int buttonX=0;
for (int i=0; i<100; i++) {
UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(buttonX, 0, scrollYearWidth/5, 30)];
[btn.titleLabel setFont:[UIFont fontWithName:#"HelveticaNeue" size:14.0]];
int mod=i%2;
if (mod==1) {
[btn setTitle:#"-" forState:UIControlStateNormal];
[btn.titleLabel setTextColor:[UIColor whiteColor]];
}
else
{
[btn addTarget:self action:#selector(yearClick :) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:[NSString stringWithFormat:#"%li",(long)backYear] forState:UIControlStateNormal];
if (backYear==year) {
btnCurrentYear=btn;
[btn setBackgroundImage:[UIImage imageNamed:#"yearSelect"] forState:UIControlStateNormal];
}
backYear++;
}
[scrollYear addSubview:btn];
btnLast=btn;
buttonX=buttonX+btn.frame.size.width;
}
[scrollYear setContentSize:CGSizeMake(btnLast.frame.origin.x+btnLast.frame.size.width, scrollYearHeight)];
[scrollYear setContentOffset:CGPointMake(btnCurrentYear.frame.origin.x-(btnLast.frame.size.width*2),0)];
My problem is which constraint I should use inorder to display this correctly in every device. Here I have attached how it shows on 6s and ipad pro. How can I make the ipad pro visual same as the 6s.
Button loks in 6s
Button looks in ipad pro
Please help me.
Thanks

This is because your button background width got scaled. you need to use resizable image to keep the round edge. Change your background image with follow:
UIImage* backgroundImage = [UIImage imageNamed:#"yearSelect"];
backgroundImage = [backgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backgroundImage.size.width/2-1, 0, backgroundImage.size.width/2)];
[btn setBackgroundImage:backgroundImage forState:UIControlStateNormal];

Related

in landscape no showing image and button

I have added one imageview, 2 button in one view controller in code. In portrait mode its working well. But in landscape mode not able to see the image and button.
#implementation ViewController {
UIImageView* imgView; // your UIImageView
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self navigationController] setNavigationBarHidden:YES animated:YES];
UIImage* img1 = [UIImage imageNamed:#"11.jpg"];
UIImage* img2 = [UIImage imageNamed:#"s2.jpg"];
imgView = [[UIImageView alloc] initWithFrame:self.view.frame]; // create a UIImageView with the same size as the view.
imgView.animationImages = #[img1, img2]; // use a nice NSArray literal to pass in your images.
imgView.animationDuration = 2.0*2.0; // 2 seconds for each image (x3 images)
[self.view addSubview:imgView]; // add UIImageView to view
[imgView startAnimating]; // start animating
// button one
UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0.0, self.view.frame.size.height-50, self.view.frame.size.width/2 , 50.0)];
[button setBackgroundColor:[UIColor colorWithRed:188/255.0f green:155/255.0f blue:211/255.0f alpha:0.6f]];
[button setTitle:#"Sign Up" forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; // title color
[button addTarget:self action:#selector(method:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
// Button Two
UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height-50, self.view.frame.size.width/2 , 50.0)];
[button1 setBackgroundColor:[UIColor colorWithRed:188/255.0f green:155/255.0f blue:211/255.0f alpha:0.6f]];
[button1 setTitle:#"Sign In" forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(method:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; // title color
[self.view addSubview:button1];
// Border color for one button
UIView *leftBorder = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 1, button.frame.size.height)];
leftBorder.backgroundColor = [UIColor colorWithRed:237/255.0f green:211/255.0f blue:246/255.0f alpha:0.6f];
[button1 addSubview:leftBorder];
}
Why its not working well for landscape. Please help me, for portrait its working well. For landscape its not working ..
It's not working in landscape because when we rotate to landscape the button and image view, as you have positioned them in your code, are located below the bottom of the screen.
You will have to implement Auto Layout. It will fix the problem. Please avoid hard coding the positions as will create problems in UI. If you want to hard code the points then make your app in either portrait mode or landscape mode.
In auto layout constraints can be set programmatically as well. Just check which is feasible for you and implement it.

How To Move scrollview(horizontal) based on In its subview position

I am adding a series of buttons to my scrollview,So on clicking button I want to highlight that one and deselect remaining all. So every thing Works fine. But i need one more behaviour like if Second button is highlighted I want to show some part of third button so that user knows there is one more category.
float offset=0;
for(int i=0;i<[arrMaincat count];i++)
{
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.tag=i;
btn.titleLabel.font=[UIFont systemFontOfSize:12];
btn.titleLabel.lineBreakMode=UILineBreakModeTailTruncation;
NSString *Categoryname=[[arrMaincat objectAtIndex:i] objectForKey:#"Name"];
CGSize constraint=CGSizeMake(1000, 30);
CGSize size1 = [Categoryname sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
btn.frame=CGRectMake(offset, 0, size1.width, 30);
[btn setTitle:Categoryname forState:UIControlStateNormal];
[btn setTitle:Categoryname forState:UIControlStateSelected];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setTitleColor:UIColorFromRGB(0Xe08043) forState:UIControlStateSelected];
[btn addTarget:self action:#selector(CategoryChanged:) forControlEvents:UIControlEventTouchUpInside];
offset=btn.frame.origin.x+btn.frame.size.width+10;
[self.SliderScroll addSubview:btn];
}
self.SliderScroll.contentSize=CGSizeMake(offset, SliderScroll.frame.size.height);
Remaning Code http://pastie.org/10277453
Here is my screenshot https://www.dropbox.com/s/xpq9vy39eecab1g/Screen%20Shot%202015-07-07%20at%205.34.15%20pm.png?dl=0
Thank you
So whats the problem, its a simple calculation of content offset. If the button being highlighted is the last button in the scroll view's current visible frame you can add some hardcoded value (lets say 50) to the content offset.x

keep label text aligned center to screen while scrolling uilabel with view iOS?

I have a UITableView and 10 sections in it.
For each section I have a custom header.
In custom header I have a label as heading of section with text value date.
Table content size is (450,1000).
Here my label with text is also scrolling, but I want my label text should aligned center to screen and it should not scroll horizontally with table.
Thanks in advance.
After knocking my head for hours finally i got this solution.
Simply i used
(void)scrollViewDidScroll:(UIScrollView *)scrollView*
method and changed my label frame with table view content offset.
myLabel.frame = CGRectMake(tableview.contentoffset.x, 0, deviceHeight, 27);
It will keep my label at same position to screen, logically it is changing but will look like its stable at same position.
That behavior is only common when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.
May be the following links will help you to solve your problem:
1. UITableView with fixed section headers
2. https://corecocoa.wordpress.com/2011/09/17/how-to-disable-floating-header-in-uitableview/
- (void)addButtonsOnScrollViewHorizontal:(int)postion :(UIScrollView*)scrollView
{
[scrollView setShowsVerticalScrollIndicator:NO];
float x = 30;
for (int i = 1; i <=postion; i++)
{
UIButton *button= [UIButton buttonWithType:UIButtonTypeCustom];
[button setTag:i];
[button setTitle:[NSString stringWithFormat:#"%i",i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor colorWithRed:26.0f/255.0f green:188.0f/255.0f blue:156.0f/255.0f alpha:100.0f] forState:UIControlStateSelected];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:18.0f];
CGSize maxSize = CGSizeMake(button.frame.size.width, FLT_MAX);
CGRect labRect = [button.titleLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:button.titleLabel.font} context:nil];
[button setFrame:CGRectMake(x, 0, labRect.size.width+10, 30)];
[button addTarget:self action:#selector(scrollViewDaysbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
if (i==postion)
{
[_scrollViewDays setContentOffset:CGPointMake (button.frame.origin.x+button.frame.size.width/2-70, 0) animated:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
[button setSelected:YES];
currentSelectionDays =i;
}
[scrollView addSubview:button];
x +=labRect.size.width+20;
}
scrollView .contentSize = CGSizeMake(x, 0);
}
-(void)scrollViewDaysbtnClicked:(UIButton*)sender
{
for (UIButton *button in _scrollViewDays.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
if (button.tag == sender.tag)
{
[_scrollViewDays setContentOffset:CGPointMake (button.frame.origin.x+button.frame.size.width/2-70, 0) animated:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
[button setSelected:YES];
currentSelectionDays =(int)sender.tag;
}else
{
[button setSelected:NO];
button.titleLabel.font =[UIFont fontWithName:#"HelveticaNeue-Bold" size:18.0f];
}
}
}
}
use it....

ios 8 - scroll does not work

I am using UIScrollView . At run time I am adding UIButton into scrollview. In iOS 7 it work perfectly but in iOS 8 I am getting problem on scrolling (it is very hard to scroll )..
Here is my code . Please suggest me What am I doing wrong or in iOS 8 is there any new property? .
-(void)renderAllCatealogue:(NSArray *)catalogueArr
{
[[scollViewCatlog subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
int x=0;
for (NSDictionary *dict in catalogueArr)
{
UIView *view =[[UIView alloc]initWithFrame:CGRectMake(x, 8, 1, 16)];
[view setBackgroundColor:[UIColor whiteColor]];
[scollViewCatlog addSubview: view];
//calculate width
UIFont *font=[UIFont fontWithName:BOLD_FONT size:15];
CGFloat width=[[CommonUISetting sharedInstance]widthOfString:[dict valueForKey:#"catalogTitle"] withFont:font];
UIButton * btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(x+10, 1, width, 30)];
[btn setTitle:[dict valueForKey:#"catalogTitle"] forState:UIControlStateNormal];
[btn setTag:[[dict valueForKey:#"catalogId"] integerValue]];
[btn.titleLabel setFont:font];
[btn addTarget:self action:#selector(catlogBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn.titleLabel setFont:[UIFont fontWithName:BOLD_FONT size:15]];
[btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[scollViewCatlog addSubview:btn];
x=x+width +15;
}
[scollViewCatlog setContentSize:CGSizeMake(x, 1)];
}
i got solution .
I create a subclass of UIScrollview and add this method in it.
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
I think you should use UICollectionView in order to generate something you want. UICollectionView allows to create vertical as well as horizontal infinite scroll panel. It is similar as the UITableView, you just have to setup some DataSource Methods and Delegate Methods.
look here for sample of UICollectionView

UIButton Image + Text IOS

I need a UIButton with image & text. Image should be in the top & text comes under the image both should be clickable.
I see very complicated answers, all of them using code. However, if you are using Interface Builder, there is a very easy way to do this:
Select the button and set a title and an image. Note that if you set the background instead of the image then the image will be resized if it is smaller than the button.
Set the position of both items by changing the edge and insets. You could even control the alignment of both in the Control section.
You could even use the same approach by code, without creating UILabels and UIImages inside as other solutions proposed. Always Keep It Simple!
EDIT: Attached a small example having the 3 things set (title, image and background) with correct insets
I think you are looking for this solution for your problem:
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:#"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:#"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:#selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like
...the rest of the customisation of the button is your duty now, and don't forget to add the button to your view.
UPDATE #1 and UPDATE #2
or, if you don't need a dynamic button you could add your button to your view in the Interface Builder and you could set the same values at there as well. it is pretty same, but here is this version as well in one simple picture.
you can also see the final result in the Interface Builder as it is on the screenshot.
Xcode-9 and Xcode-10 Apple done few changes regarding Edge Inset now, you can change it under size-inspector.
Please follow below steps:
Step-1:
Input text and select image which you want to show:
Step-2:
Select button control as per your requirement as shown in below image:
Step-3:
Now go-to size inspector and add value as per your requirement:
swift version:
var button = UIButton()
newGameButton.setTitle("Новая игра", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50
In my case, I wanted to add UIImage to the right and UILabel to the left. Maybe I can achieve that by writing code (like the above mentioned), but I prefer not to write code and get it done by using the storyboard as much as possible. So this is how did it:
First, write down something in your label box and select an image that you want to show:
And that will create a button looking like this:
Next, look for Semantic and select Force Right-to-Left (If you don't specify anything, then it will show the image to the left and label to the right like the above image):
Finally, you'll see UIImage to the right and UILabel to the left:
To add space between a label and an image, go to the Size inspector and change those values depending on your requirement:
That's it!
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
but following code will show label above and image in background
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
There is no need to use label and button in same control because UIButton has UILabel and UIimageview properties.
Use this code:
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(0, 10, 200, 52)];
[sampleButton setTitle:#"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:#"redButton.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton]
You should create custom imageview for image and custom label for text and you add to your button as subviews. That's it.
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);
[yourButton addTarget:self action:#selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:#"images.jpg"];
[yourButton addSubview:imageView1];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = #"ButtonTitle";
[yourButton addSubview:label];
For testing purpose, use yourButtonSelected: method
-(void)yourButtonSelected:(id)sender{
NSLog(#"Your Button Selected");
}
I think it will be helpful to you.
Use this code:
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.imageView.frame=CGRectMake(0.0f, 0.0f, 50.0f, 44.0f);///You can replace it with your own dimensions.
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 35.0f, 50.0f, 44.0f)];///You can replace it with your own dimensions.
[button addSubview:label];
I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :
-(void)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.
Make UIImageView and UILabel, and set image and text to both of this....then Place a custom button over imageView and Label....
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"search.png"]];
imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
[self.view addSubview:imageView];
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = #"raj";
[self.view addSubview:yourLabel];
UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:#selector(#"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];
It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal.
That's it.
[btn setBackgroundImage:[UIImage imageNamed:#"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:#"Click Me" forState:UIControlStateNormal];

Resources