iOS - center content of UIView - ios

I am trying to create UIView with image and number. I want to center them. For now I have this code:
CGRect likesRect = CGRectMake(0,152, screenWidth / 2, 30);
MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect];
UIView *likesView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
likesView.center = CGPointMake(screenWidth / 4, 20);
UIImageView *likeImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
likeImage.image = [UIImage imageNamed:#"favorite.png"];
UILabel *likesLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, screenWidth / 2, 20)];
[likesLabel setTextColor:[UIColor whiteColor]];
[likesLabel setBackgroundColor: [UIColor clearColor]];
[likesLabel setText:[actualPlace.Favorites stringValue]];
[likesView addSubview:likeImage];
[likesView addSubview:likesLabel];
[likesRoundedRect addSubview:likesView];
[viewController.view addSubview:likesRoundedRect];
For now it's working good but I am setting width of likesView to exact value and I guess this goes bad when I don't have number with one or two letters but more. How can I fix this? How to center content of UIView if there are two or more components with side by side? Or how can I set UIView to dynamically change width by content? Thanks

I am not writing full code but you try with following code,
CGRect likesRect = CGRectMake(0,152, screenWidth / 2, 30);
MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect];
CGSize likeViewSize = CGSizeMake(50,30);
UIView *likesView = [[UIView alloc] init];
likesView.frame = CGRectMake(likesRoundedRect.frame.size.width/2 - likeViewSize.width/2,likesRoundedRect.frame.size.height/2 - likeViewSize.height/2,likeViewSize.width,likeViewSize.height);
I have centered the likesView on its parentview. you have to do same thing for label and imageview if you want to center them on their parentview (likesView)

UIView and its subclasses has a property called center :
CGPoint center1 = CGPointmake(self.view.bounds.size.width/2,
self.view.bounds.size,height/2) ;
subview.center = center1;
The following discussion is from the Apple documentation on UIView:
#property(nonatomic) CGPoint center
Discussion
The center is specified within the coordinate system of its superview and is measured in points. Setting this property changes the values of the frame properties accordingly.
Changing the frame rectangle automatically redisplays the receiver without invoking the drawRect: method. If you want the drawRect: method invoked when the frame rectangle changes, set the contentMode property to UIViewContentModeRedraw.
Changes to this property can be animated. Use the beginAnimations:context: class method to begin and the commitAnimations class method to end an animation block.
Availability
Available in iOS 2.0 and later.
See Also
#property frame
#property bounds
#property transform
Related Sample Code
AVLoupe
Handling Touches Using Responder Methods and Gesture Recognizers
iAdInterstitialSuite
iAdSuite
RosyWriter
Declared In
UIView.h

Related

IOS/Objective-C: Subview of Subview not displaying

I am trying to create a chart where a bar in the form of a UIView displays on top of a background UIView. I'd like both to display on top of the UIView for the whole screen. I have done this before successfully, but while I can get the first view to display, I somehow can't get my code to display the bar. Could it have something to do with setting the color? Or can anyone suggest why the second subview is not displaying.
My code:
//Make background box:
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat graphWidth = screenWidth-40;
CGFloat graphHeight = 160;
CGRect graphBounds =CGRectMake(20, 200, graphWidth, graphHeight);
float tableStartY = graphBounds.origin.y;
UIView *graphBox = [[UIView alloc] initWithFrame:graphBounds];
graphBox.backgroundColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:0.2]; graphBox.layer.borderWidth = 1;
graphBox.layer.borderColor = [UIColor blueColor].CGColor;
//Make Bar
CGFloat barWidth = 20;
CGFloat barHeight = 100;
CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);
UIView *barView = [[UIView alloc] initWithFrame:aBar];
barView.backgroundColor = [UIColor blueColor];
barView.layer.borderWidth = 1;
barView.layer.borderColor = [UIColor redColor].CGColor;
// [graphBox addSubview:barView];
[self.view addSubview: graphBox];
If I run the above code, it displays the graphBox. If I add the bar directly to the view as a subView instead of the graphBox, the bar displays. However, if I uncomment out the line shown and add the barView first to the graphBox and then add the graphBox to the view, the barView does not display.
Thanks in advance for any suggestions.
If I understand correctly what you need to do, you should replace
CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);
with
CGRect aBar = CGRectMake(20, 1, barWidth, barHeight);
[edit: and obviously uncomment the addSubview line]
Perhaps this is an accident in your posted code, but you have specifically commented out where the barView would be added to the screen.
// [graphBox addSubview:barView];
In addition, as another answer lists, your offset is incorrect if you are adding barView to graphBox. If you add it to self.view instead, your offset is correct.
So, you've got two choices, depending on the containment you desire in your view hierarchy:
CGRect aBar = CGRectMake(20, 1, barWidth, barHeight);
// ...
[graphBox addSubview:barView];
or
CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);
// ...
[self.view addSubview: graphBox];
[self.view addSubview:barView];
Note that in the second option, the order is important to get the barView to display over top of the graphBox as they will be siblings.

Set a UIView in a fixed proportional position from the Right Edge of screen iOS

Say, I have a UIImageView or any object and I set it in a UIView as subView with CGRectMake like this:
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(266, 0, 30, 30)];
[imgView setImage:[UIImage imageNamed:[self.imageDicKey objectAtIndex:section]]];
[headerView addSubview:imgView];
Here I set the position of my imgView like CGRectMake(266, 0, 30, 30)]; and it counts it's position form the left x position (which is 266). What If I want to set my imgView's position from right side of the screen? So that,in different width of iPhone screen it shows in a same ratio position. But which will be counted it's position from right edge.
Thanks a lot in advanced.
I would recommend not hard coding the exact positions and instead calculating the x and y. That way it will help for different sized screens so it's not an exact position and rather it's based upon the views' size.
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
CGFloat padding = 20; // amount for padding
CGSize size = CGSizeMake(30, 30); // size of imageView
CGPoint startPos = CGPointMake(headerView.frame.size.width - padding - size.width, 0); // starting position for imageView
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(startPos.x, startPos.y, size.width, size.height)]; [imgView setImage:[UIImage imageNamed:[self.imageDicKey objectAtIndex:section]]]; [headerView addSubview:imgView];
Well, since the ImageView's width is 30 and the x coordinate is 266 from the left side, it makes the x coordinate from the right side 296.

Rotate a UIlabel to make it vertical

I have a UILabel. I need to rotate it programmatically.
I have my horizontal UILabel, for example with frame: x:0, y:0, w: 200, h:80.
Now I would like to rotate the label to make it vertical:
I try this code:
[self setTransform:CGAffineTransformMakeRotation(M_PI_2 / 2)];
I can see the contained text rotated. But I would like to rotate the whole frame: With my code, the UILabel continues to have the same frame.
Try this working code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 200, 80)];
//set background color to see if the frame is rotated
[label setBackgroundColor:[UIColor redColor]];
[label setText:#"Text Here"];
label.transform=CGAffineTransformMakeRotation( ( 90 * M_PI ) / 180 );
[self.view addSubview:label];
Hope it helps
If you prefer set the label position and size visually in you xib or storyboard do the following:
Set the labels position and size in the interface builder like you want them to stay after the rotation.
Rotate the label and set the frame again:
-(void)rotateLabel:(UILabel*) label
{
CGRect orig = label.frame;
label.transform=CGAffineTransformMakeRotation(M_PI * 3/2);//270º
label.frame = orig;
}
Your Label is a square(w:100,h:100).So your label has transformed, but you can't see the change,because the width is equal to the height.

UIImageView and autolayout

I have a view that is set up nicely using autolayout. The view contains a series of labels stacked from top to bottom. I am allowing the intrinsic size of these labels to determine the size of the view.
The final step is to add a background from an image. I started by trying the colorWithPatternImage method on UIColor but this isn't quite what I am looking for. I do not want to tile the image, and I can not guarantee it will always be larger than the intrinsic size of the view.
Similarly, adding a uiImageView to the view itself doesn't quite work. The view will expand to accommodate the image when I want to keep the intrinsic size based on the labels.
I guess what I am looking for is the following.
1) The background should have no effect on the size of the view.
2) The image should be scaled to fill the view but in it's original aspect ration (so cropping edges if necessary).
Any ideas appreciated.
In my case, I needed it for a UIImageView inside a dynamically-sized view in a UITableViewCell, but the image refused to shrink below its instristic size and instead worked as a minimum-size constraint for the superview. The only way I could get it ignore the intristic size is by lowering the priority at which it is enforced, right after creating the cell:
[imageView setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
forAxis:UILayoutConstraintAxisHorizontal];
[imageView setContentCompressionResistancePriority:UILayoutPriorityDefaultLow
forAxis:UILayoutConstraintAxisVertical];
After this, all my constraints magically started working. In the OP's case, setting UIViewContentModeScaleAspectFill is also required, as per Mundi's answer.
In Interface Builder, add a UIImageView as the first subview to the view. Make sure its size always matches the view.
Then, in Interface Builder or code, set the contentMode:
backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
Here's how I would approach this. Hopefully it helps. :)
CGRect contentFrame = CGRectMake(0, 0, self.view.frame.size.width, 0); // This will be the frame used to create the background image view.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(20, 20, 20, 20); // The margins by which the labels will be inset from the edge of their parent view.
CGFloat labelHeight = 21;
CGFloat verticalGap = 8; // The vertical space between labels
CGFloat y = contentInsets.top;
int numberOfLabels = 10;
for (int i = 0; i < numberOfLabels; i++) {
CGRect frame = CGRectMake(contentInsets.left, y, self.view.frame.size.width - (contentInsets.left + contentInsets.right), labelHeight);
UILabel *label = [[[UILabel alloc] initWithFrame: frame] autorelease];
// customize the label here
[self.view addSubview: label];
contentFrame = CGRectUnion(contentFrame, label.frame);
y += labelHeight + verticalGap;
}
contentFrame.size.height += contentInsets.bottom;
UIImageView *backgroundImageView = [[[UIImageView alloc] initWithFrame: contentFrame] autorelease];
[backgroundImageView setClipsToBounds: YES];
[backgroundImageView setContentMode: UIViewContentModeScaleAspectFill];
[backgroundImageView setImage: [UIImage imageNamed: #"background_image.png"]];
[self.view insertSubview: backgroundImageView atIndex: 0];

How to center a UILabel on UIView

How can I center the UILabel on the UIView? I am using the following code
float width = weatherView.bounds.size.width;
float height = weatherView.bounds.size.height;
[self.label setFrame:CGRectMake(width-100,height-100, 100, 100)];
How about:
[self.label setCenter:view.center];
If the label is a subview of view:
[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]
Don't use view.center unless the label and view have the same superview.
If there is no immediate connection, then you'll have to transform view's center to the coordinate space of label's parent. Then you could use PengOne's answer with the transformed point.
Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content.
cell.menuLabel.textAlignment = NSTextAlignmentCenter;
A better posible solution is:
First: If you are doing this programmatically you'll need to initialize with frame and some customizations:
// Simple example
int yPosition = 10;
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0, yPosition, self.view.frame.size.width, 0)];
[label setText: #"Testing..."];
[label setBackgroundColor: [UIColor clearColor]];
[label setNumberOfLines: 0];
[label sizeToFit];
Second: If a label what you are trying to center you can just run this after setNumberOflines selector called and 0 value assigned, your text will have all lines needed, and sizeToFit method called to have a good customization, and finally:
[self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];
This will center only the X axis, and the Y axis will stay as you desired in the frame initialization.
PS: It's also valid if not a UILabel but depends on the control you are using will need another simple customization or neither, and if you only want to center programmatically but interface builder designed, just need to run the second code.
PengOne / Alex Lockwood's answer is simple and useful. If you intend to support rotation, add the following to keep it centered:
[self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
Something like this should do the trick...
Make sure that your label is set to have centered alignment and is sufficiently big/wide to handle your text string.
float viewWidth = weatherView.frame.size.width;
float viewHeight = weatherView.frame.size.height;
float labelWidth = label.frame.size.width;
float labelHeight = label.frame.size.height;
float xpos = (viewWidth/2.0f) - (labelWidth/2.0f);
float ypos = (viewHeight/2.0f) - (labelHeight/2.0f);
[label setFrame:CGRectMake(xpos,ypos,labelWidth,labelHeight)];
I think that should do what you are asking for.
There are two possibility if your UILabel is added via .xib or else added programmatically .
If first case i.e added via .xib then you can set the position from xib file size inspector tab with the 'Arrange' property
And if second case persist then you can set as --- [self.label setCenter:view.center];

Resources