How to set alignment for UIScrollView in ios - ios

i am creating an application, where i am using UIScrollView for displaying the number of available colors of each product. I am getting number of available colors at run time, so i have used for loop and displaying on my scroll view. Its working fine, but the problem if i am getting only one available color then my output is coming as below screen :
But the output should be as below screen :
It seems like i need to do kind of center alignment for my UIScrollView, so every available color will suppose to display from center. here is my code :
UIScrollView *availableColorScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
availableColorScrollView.backgroundColor = [UIColor clearColor];
availableColorScrollView.showsHorizontalScrollIndicator = YES;
availableColorScrollView.showsVerticalScrollIndicator=NO;
availableColorScrollView.pagingEnabled = YES;
for (int i = 0; i < arrayAvlbleColors.count; i++) {
CGRect frame;
frame.origin.x = 23 * i;
frame.origin.y = 0;
frame.size = availableColorScrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
UILabel *label = [[UILabel alloc] init];
[label setFrame:CGRectMake(15, 14, 16, 16)];
[label.layer setCornerRadius:8];
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
}
[self.view addSubview:availableColorScrollView];
availableColorScrollView.contentSize = CGSizeMake(24 * arrayAvlbleColors.count, availableColorScrollView.frame.size.height);
Please suggest me to achieve my output, Thanks!

this is the simple answer but working fine if u taken any Mainview or subview or else,
set the frame size/2 for height and width it automatically set it into center of the subview.
here i used static color , customize urself
just change your line this
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
into
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
//use any one
//option no 1:
//[label setCenter:subview.center];
//option no 2:
[ label setCenter:CGPointMake(subview.frame.size.width / 2, subview.frame.size.height / 2)];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
final out put is

You can calculate your scrollview content to be placed in centre like this:
float contentWidth = 23 * arrayAvlbleColors.count;
Now you have content width to subtract from scrollView's width
float centerPadding = 0.0f;
float width = availableColorScrollView.frame.size.width;
centerPadding = width - contentWidth;
if(centerPadding < 0)
{
//content cannot be placed in center as content is bigger than width
centerPadding = 0.0f;
}
We have padding to center our content in scrollView, so use it in for loop like this :
frame.origin.x = (23 * i) + centerPadding;

Related

How to programmatically sizeToFit width AND height on UILabel?

I'm programmatically creating multi-line UILabels ([label setNumberOfLines:0];).
The built-in sizeToFit method of UILabel works great for 1 line UILabels, but for multi-line text, it sets the height properly, but the width is set too small, causing longer text lines to wrap.
I don't know the label width until after the user enters their text. I want to resize the labels to fit the width of the longest line of text. And per #DonMag's comment, I also want to restrict the label to not be wider than the screen.
I tried different lineBreakMode settings but there isn't a 'nowrap' option.
I've searched SO and there are many related solutions but none that solve the problem of sizeToFit for both width and height.
Is there a way to programmatically size a multi-line UILabel to fit BOTH the width AND the height of the text?
You can do this with boundingRectWithSize...
Add your label to the view and give it a starting width constraint (doesn't really matter what value, as it will be changed).
Keep a reference to that width constraint (IBOutlet works fine if you're using IB).
Don't give it a height constraint.
When you set the text of the label, you can use this to change its width:
// get the font of the label
UIFont *theFont = _theLabel.font;
// get the text of the label
NSString *theString = _theLabel.text;
// calculate the bounding rect, limiting the width to the width of the view
CGRect r = [theString boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: theFont}
context:nil];
// change the constant of the constraint to the calculated width
_theWidthConstraint.constant = ceil(r.size.width);
// NOTE: If you are *not* using auto-layout,
// this same calculation can be used to explicitly set
// the .frame of the label.
Edit:
As per the OP's requirement, a complete, runnable example -- using code only, no storyboards / IB -- can be found here: https://github.com/DonMag/MultilineLabelFitWidth
Edit 2:
GitHub project updated... now includes examples for both manual frame setting and auto layout / constraints.
With some more experimentation, I found something that does the trick that I have not seen in SO (yet...). In general it works like this:
Find the longest text line
Set numberOfLines to 1 (temporarily)
Set label text to longest text line
Call label.sizeToFit (sets label width for longest line)
Set numberOfLines to 0 (multi-line)
Set label text to full multi-line text
Call label.sizeToFit (sets label height for all lines)
Voila! Now your UILabel is sized to fit your multi-line text.
Here is an example (demo project on GitHub: UILabelSizeToFitDemo):
- (UILabel *)label = nil;
- (void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
[_label setBackgroundColor:[bananaColor colorWithAlphaComponent:0.9f]];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// split lines
NSArray *lines = [notes componentsSeparatedByString:#"\n"];
NSString *longestLine = lines[0]; // prime it with 1st line
// fill a temp UILabel with each line to find the longest line
for (int i = 0; i < lines.count; i++) {
NSString *line = (NSString *)lines[i];
if (longestLine == nil || line.length > longestLine.length) {
longestLine = line;
}
}
// force UILabel to fit the largest line
[_label setNumberOfLines:1];
[_label setText:longestLine];
[_label sizeToFit];
// make sure it doesn't go off the screen
if (_label.frame.size.width > screenWidth) {
CGRect frame = _label.frame;
frame.size.width = screenWidth - 20;
_label.frame = frame;
}
// now fill with the actual notes (this saves the previous width)
[_label setNumberOfLines:0];
[_label setText:notes];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
[_label setCenter:center];
}
UPDATE: Here is an alternate complete solution, using the boundinRectWithSize from the code snippet by #DonMag:
-(void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
_label.backgroundColor = [bananaColor colorWithAlphaComponent:0.9f];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// set new text
_label.text = notes;
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// calculate the bounding rect, limiting the width to the width of the view
CGRect frame = [notes boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: _label.font}
context:nil];
// set frame and then use sizeToFit
[_label setFrame:frame];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
[_label setCenter:center];
}

Display some images on album cover in iOS

i want to display some images on album cover on my app like bellow image.
EDIT:-
i want to display this view in UICollectionViewCell and collectionView scrollDirection Horizontal with paging enabled.
any help will be appreciated. and thanks in advance.
I do not know if you understand the question correctly.
If you want to do what I see on the picture, so try this:
UIView *cover = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 500, 500)];
cover.backgroundColor = [UIColor blueColor];
int width = 200;
int height = 350;
int posx = 100;
int posy = 50;
for (int i = 0; i < 10; i++) {
//craete images
UIView *imagebg = [[UIView alloc] initWithFrame:CGRectMake(posx + arc4random_uniform(20), posy + arc4random_uniform(20), width, height)];
imagebg.backgroundColor = [UIColor whiteColor];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, width - 40, height - 50)];
image.image = [UIImage imageNamed:#"loading-screen.png"];
[imagebg addSubview:image];
//rotate
double rads = arc4random_uniform(100)/10;
CGAffineTransform transform = CGAffineTransformRotate(imagebg.transform, rads);
imagebg.transform = transform;
//add as subview
[cover addSubview:imagebg];
}
[self.view addSubview:cover];

Fill view with buttons at random positions

i want to fill area (UIView) with buttons(UIButton) so that they do not intersect with each others.
My idea:
create initial button at random position in view;
fill view with other buttons from initial button (count < 20) that they do not intersect ~10 pixels from each other.
What have i done so far:
I created method:
-(void)generateButtonsForView:(UIView *)view buttonCount:(int)count
{
//get size of main view
float viewWidth = view.frame.size.width;
float viewHeight = view.frame.size.height;
//set button at random position
UIButton *initialButton = [[UIButton alloc] initWithFrame:CGRectMake(arc4random() % (int)viewWidth,
arc4random() % (int)viewHeight,
buttonWidth, buttonHeight)];
[initialButton setBackgroundImage:[UIImage imageNamed:#"button"] forState:UIControlStateNormal];
[view addSubview:initialButton];
// set count to 20 - max number of buttons on screen
if (count > 20)
count = 20;
//fill view with buttons from initial button +- 10 pixels
for (int i=0;i<=count;i++)
{
//button
UIButton *otherButtons = [[UIButton alloc] init];
[otherButtons setBackgroundImage:[UIImage imageNamed:#"button"] forState:UIControlStateNormal];
...//have no idea what to do here
}
}
So i'm confused on the place where i want to generate the position of the other buttons, depending on the initial button. I do not know how to generate theirs position that they were at a distance of 5-10 pixels from each other... Any ideas how to realise this? Thanks!
Here's an example with views rather than buttons, but the concept is the same. I use CGRectInset to give the new potential view a buffer of 10 points around it, then look for whether the new view intersects any of the other views. If there's no intersection, add the subview, if there is, try again with a new random location.
-(void)generateButtonsForView {
float viewWidth = self.view.frame.size.width;
float viewHeight = self.view.frame.size.height;
UIView *initialView = [[UIView alloc] initWithFrame:CGRectMake(arc4random() % (int)viewWidth, arc4random() % (int)viewHeight, 50, 30)];
initialView.backgroundColor = [UIColor redColor];
[self.view addSubview:initialView];
int numViews = 0;
while (numViews < 19) {
BOOL goodView = YES;
UIView *candidateView = [[UIView alloc] initWithFrame:CGRectMake(arc4random() % (int)viewWidth, arc4random() % (int)viewHeight, 50, 30)];
candidateView.backgroundColor = [UIColor redColor];
for (UIView *placedView in self.view.subviews) {
if (CGRectIntersectsRect(CGRectInset(candidateView.frame, -10, -10), placedView.frame)) {
goodView = NO;
break;
}
}
if (goodView) {
[self.view addSubview:candidateView];
numViews += 1;
}
}
}

Create a dynamic row of UITextfields

I would like some help creating a dynamic row of UITextfields, I have been trying to do it myself with some success but mostly failure.
I set a number of rows between 1 - 13 and I would like to create UITextfields that fit inside the width of an iPhone frame width evenly spaced with an even gap to the left and right.
Here is what I have done so far:
- (void) displayViews {
// add scrollview
htmlContainerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 60.0, self.view.frame.size.width, 293.0)];
NSInteger viewcount = [axisString integerValue];
color = 200;
for(int i = 0; i< viewcount; i++) {
color = color + 20;
NSLog(#"%f", color);
CGFloat y = i * 91;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y,self.view.frame.size.width, 90.0)];
view.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:(1.0/i)];;
[htmlContainerScrollView addSubview:view];
int cutCount = [cutsString integerValue];
int positions = (self.view.frame.size.width/cutCount);
for (int i = 0; i < cutCount; i++) {
//first one
UITextField *cutField = [[UITextField alloc] initWithFrame:CGRectMake((positions*i)+(20/2), 25, 20, 20)];
cutField.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
cutField.font = [UIFont fontWithName:#"Helvetica-Bold" size:25];
cutField.backgroundColor=[UIColor whiteColor];
[view addSubview:cutField];
}
}
htmlContainerScrollView.contentSize = CGSizeMake(self.view.frame.size.width, 91 *viewcount);
[self.view addSubview:htmlContainerScrollView];
}
The biggest problem with mine is that it does not evenly space them; they are always to the left.
change your cutField's frame x coordinate value calculation from
(positions*i)+(20/2)
to
((positions*i)-(20/2)+(positions/2)).
that should do the trick.
it's just a matter of the x coordinate calculation and i am sure there is room to optimize that a bit.

IOS Add subview on viewDidLoad

i have a problem when i'm trying to add subviews to a UIScrollView on viewDidLoad.
I'm using this code to programmatically add the UIImageViews to the scrollView:
- (void)viewDidLoad {
[super viewDidLoad];
NSInteger const_width = 100;
NSInteger numberOfViews = 4;
CGRect theFrame = [self.scrollView frame];
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * const_width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin,theFrame.origin.y,const_width,110)];
UIImage *image = [UIImage imageNamed:#"cocoloco.jpg"];
[imageView setImage:image];
//[self.scrollView addSubview:imageView];
imageView.tag = i;
CGRect rect = imageView.frame;
rect.size.height = 110;
rect.size.width = 110;
imageView.frame = rect;
[self.scrollView addSubview:imageView];
}
self.scrollView.contentSize = CGSizeMake(const_width * numberOfViews, 110);}
But i get the current view:
It seems that the scroll view frame takes its position regardless the 3 yellow tabs (that are a special TabBarController) so i get a wrong frame origin from the UIScrollView and therefore the UIImageViews are wrong positioned.
Any idea?
I don't know exactly how to do it, but add the height of the frame to the "Y" position of your rectangle. Something like this:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin,theFrame.origin.y + (theFrame.height),const_width,110)];
To get the scrollview below the navigation bar at the top, try
self.scrollview.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
Then position the table below the scrollview by setting it's origin base on the scrollview origin and height:
CGRect frame = tableView.frame;
frame.origin.y = self.scrollview.frame.origin.y + self.scrollview.frame.size.height;
tableView.frame = frame;
You should move any resizing or layout of your UI to the -(void)layoutSubviews method and this should sort your problem correctly.

Resources