Increase UIView's frame size at the left edge - iphone

I have an UIView that can grow dynamically in width. The view also have subviews located inside it's bounds.
Default behavior seems to be that when the view's frame grows along the x axis, increasing frame.size.width, it always grows at the right edge, keeping the subviews fixed as if there were a fix left margin. However, when I want to expand the view on the left edge this doesn't work because of this behavior. In this case I want it to behave in a mirrored way, as if there were a fix right margin. I could of course "manually" move all subviews so it looks like that is the case, but that seems really awkward since there could be plenty of them.
So I guess the question really is if there is a way to shift a views bounds relative to it's subviews? Is maybe autoresizingMask the way to do this?
Thanks.

Maybe you should take a look at the AutoresizingMask property of a UIView subclass :-)
For example, if you have a UILabel called labelVideoTitle, you could set a mask like this :
[ labelVideoTitle setAutoresizingMask:UIViewAutoresizingFlexibleWidth ];
You can by the way add 2 mask at once like :
[ labelVideoTitle setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];
Good Luck !
Edit : To increase the parent view frame size at the left edge, you could change too its X position to the left to give the impression wanted ^^ For example if you add 10 pt to the width, try modifying the X origin -10 pt :-)

In interface builder, you can graphically indicate in the CMD-3 (little ruler icon) Size Inspector what each element in your view should do when the parent view is resized: you can indicate which borders (top, left, right, bottom), the given element should "stick to" when the parent view is resized. You can also indicate whether the given element should itself resize (in either width or height) or stay the same size. Underneath the hood, this sets the autoresize mask for the UIView element you're editing, but especially for making an element stick to a particular border, Interface Builder is the way to go.
IB Size Inspector also has a neat little animation that shows you the effect on a hypothetical element (little red square) during a resize, given your settings to the left.

Related

Xcode, Is there was to constrain in a circle?

I'm working with some Text views placed on top of some UIimages. Im wanting to shape them circular but I'm not sure if theres a way to constrain them that way in a way that would stay relatively the same on different phones.
Interesting question! I think you can do something like this:
Each view is at a certain angle of the big circle. So you can constrain each view's x to the rightmost view x with a multiplier of cos(angle) and similarly constrain its y with a multiplier of sin(angle). You'll need to constrain the top and right views to the margins.
(In the image you don't have a rightmost view, maybe you can have a hidden view there.)

How to get exactly the same point on different screen sizes?

I want to call the action (go to another view) when user tap specific area of image (black dots): . Image fills whole view, content mode is 'Aspect Fit'. The problem is that when I setup it on one screen size (e.g. iPhone 8) on another the 'tap area' is shifted. I've tried to solve this with button and constraints or UITapGestureRecognizer with point conversion using screen resolution (nativeBounds), but nothing helps.
It is possible to use constraints to match the positions of the circles with UIButtons. The trick is to use the multiplier of the constraint to scale the buttons width/height and position to the screen size.
I'll describe how to do it for one button, and then you can repeat it for the others. I assume the image is 657 wide by 918 high. If I have the dimensions reversed, you'll need to substitute the actual values for the ones I have used.
Create a UIView to hold the image and buttons. Give this view an aspect ratio constraint with multiplier 657:918 which is width:height. Add the UIImageView to this view and constrain its 4 edges to the edges of the view with 0 offsets. Give this view constraints to the left and right edges of the main view and give it a vertical constraint to place it on the screen.
Get the width/height of the circle in the image and the horizontal and vertical positions of the right edge and bottom edge. For example, the topmost circle is 106 x 106 and ends at horizontal position 392 and the bottom is at 338.
Set the width of the button equal to the width of the containing view with multiplier 106:657 which is width of circle:width of the image.
Set the height of the button equal to the height of the containing view with multiplier 106:918 which is height of circle:height of the image.
Set the trailing edge of the button equal to the trailing edge of the containing view with multiplier 392:657 which is end of circle:width of image.
Set the bottom edge of the button equal to the bottom edge of the containing view with multiplier 338:918 which is bottom of circle:height of the image.
This will allow the button to stay aligned with the circle on all devices. Repeat steps 2 through 6 for the other circles.
Instead of using an image, you can try creating your own UIView subclass called BlackDotsView.
In the draw(_rect:) method, you can draw the lines. To determine where the lines start and end, you need to do some maths with the view's width and height. You calculate where all the lines end and create UIBezierPaths and then you stroke the paths.
In the initializer of BlackDotsView, you can add the dots as subviews. To make them circular, just set dotView.layer.cornerRadius to half the dot's width. Then, you can add UITapGestureRecognizers to the dot views.
You can follow the delegate pattern by creating a BlackDotsViewDelegate that has a method called dotTapped(index:). When a dot is tapped, you would call the delegate method and pass the index of the dot.

Auto Layout (Constraints) Center 2 side by side views in a parent view

I'm trying to figure out how to do this with auto layout (iOS6) and constraints.
Basically I have my large view divided up into two sections on the bottom. Inside of those sections (currently subviews) I have an image view and a label. I want to center those on both sides, with variable length text.
My head is mostly wrapped around auto layout, but I'm not sure the best approach to this. I'm inclined to think it's not possible in IB, but is in code.
Going to continue trying to figure this out, but in the meantime here is the example I'm trying to create.
Is this what you're after?
I did it by adding a view (named viewCenteredInLeftSection) within your leftSection, then adding the clock image and label as subviews with these constraints:
Make viewCenteredInLeftSection's CenterX and CenterY equal to its superview's (leftSection).
Make clockImage's Top, Bottom, and Leading edges equal to its superview's (viewCenteredInLeftSection).
Make label's Trailing edge equal to its superview's (viewCenteredInLeftSection).
Make clockImage's Trailing edge the standard distance away from label's Leading edge.
I have trouble resizing iOS UIViews in Interface Builder, so I made my example for OS X, and I was able to do so entirely in Interface Builder. If you have trouble making the above constraints in Interface Builder, let me know, and I'll post code that'll create them.
2014-08-26 Edit
Luda, here are Xcode 5's Pin and Align menus, also available in Xcode's menu bar:
Below is what my example looks like in Interface Builder. The blue view is the "parent view" from the original question, the given view in which the image and label should be centered.
I added the green view (which I named viewCenteredInLeftSection) as a subview of "parent view". Then I highlighted it and used the Align menus "Horizontal Center in Container" and "Vertical Center in Container" to create constraints to define its position.
I added the clock image as a subview of viewCenteredInLeftSection, with constraints defining its width and height. I highlighted the clock image and viewCenteredInLeftSection, then applied constraints using Align > Leading Edges, Align > Top Edges, and Align > Bottom Edges.
I added the label as a subview of viewCenteredInLeftSection, positioning it to be the standard Aqua space distance from the clock image. I highlighted the label and viewCenteredInLeftSection, then applied constraints using Align > Trailing Edges.
This was much easier to create with Xcode 5's Interface Builder versus Xcode 4's.
I figured out a way without adding another view:
[aView addConstraint:[NSLayoutConstraint constraintWithItem:viewOnLeft attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationLessThanOrEqual toItem:aView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[aView addConstraint:[NSLayoutConstraint constraintWithItem:viewOnRight attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationLessThanOrEqual toItem:aView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
You can also change the constants to create a gap between the views.
left view constraint constant: -X
right view constraint constant: +X
A solution to this is considered in stanford university lectures on ios 7.It works beautifully.Attached here that solution. (Here sdfssfg... thing is label1 and efsdfg.... thing is label2)
It took me a little while, but I figured out a pretty solid solution. I figured out the same solution John Sauer provided, but didn't want to add yet another view to wrap these in.
The answer requires three steps.
1) The width of my subview that contains the other two, which I'll call leftInfoSection, needs to be determined by it's contents. That removes the need for it to have left and right constraints to a superview (or other view) to determine it's width. That's a real key with a lot of this stuff is letting widths be defined by children.
2) I still had to have a leading constraint in IB for it to have a valid layout. (It needed to know where to place the leftInfoSection horizontally). Wire up that one constraint into your code so you can remove it. In addition to that, I had a trailing constraint GTE the vertical divider + 3.
3) The final key is to think about what information you have to work with (in code, as IB is limited). I realized that I knew the center of the horizontal divider above my section, and that the center of my leftInfoSection would be the center of that horizontal bar minus 1/4 of the horizontal bar's width. Here's the final code for both the left and right side:
// remove the unwanted constraint to the right side of the thumbnail
[self.questionBox removeConstraint:self.leftInfoViewLeadingConstraint];
// calculate the center of the leftInfoView
CGFloat left = self.horizontalDividerImageView.frame.size.width/4 * -1;
// constrain the center of the leftInfoView to the horizontal bar center minus a quarter of it to center things
[self.questionBox addConstraint:[NSLayoutConstraint constraintWithItem:self.leftInfoView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.horizontalDividerImageView attribute:NSLayoutAttributeCenterX multiplier:1 constant:left]];
// remove the unwanted constraint to the right side of the questionBox
[self.questionBox removeConstraint:self.rightInfoViewTrailingConstraint];
// calculate the center of the rightInfoView
CGFloat right = left * -1;
// constrain the center of the rightInfoView to the horizontal bar center plus a quarter of it to center things
[self.questionBox addConstraint:[NSLayoutConstraint constraintWithItem:self.rightInfoView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.horizontalDividerImageView attribute:NSLayoutAttributeCenterX multiplier:1 constant:right]];
Result:
Also, IB can be very annoying with how it automatically updates constraints. When I was trying to define the leading and trailing constraints on the subviews as 0, it would keep disconnecting one or the other and making a constraint to the superview to define the width. The trick was to leave that unwanted constraint in place temporarily, but lower its priority to 999. Then I was able to create but subview constraints to define the width.
This works pretty well but requires 2 spacer UIView's:
UIView *spacer1 = [[UIView alloc] init];
spacer1.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:spacer1];
UIView *spacer2 = [[UIView alloc] init];
spacer2.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:spacer2];
NSDictionary *views = NSDictionaryOfVariableBindings(spacer1, spacer2, imageView, label);
[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[spacer1(>=0)][imageView]-4-[label][spacer2(==spacer1)]|" options:0 metrics:nil views:views];
for (int i = 0; i < constraintsArray.count; i++) {
[self.view addConstraint:constraintsArray[i]];
}
After iOS 9, another option to achieve this is using Stack Views
There are several ways to do this. In basic terms, here is how to center 1..n items, assuming all your items have constrained sizes and are not going to grow.
Put 2 spacers on each side of your items. Anchor the spacers to the parent edges. Anchor your first and last items to the anchors. Finally, assign 1 spacer to have the width of the other spacer. You do not need to explicitly set any spacer size, as it will be solved.
spacer1 -> left=parent:left width=spacer2:width
spacer2 -> right=parent:right
yourFirstItem -> left=spacer1:right
yourLastItem -> right=spacer2:left
If spacers aren't your thing, and you and you have an odd number of items, center the middle one to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.
yourMiddleItem = centerX=parent:centerX
otherItems->yourMiddleItem<-otherItems
If spacers aren't your thing, and you have an even number of items, center the 2 inner items' edges to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.
leftMiddleItem -> right=parent:centerX
rightMiddleItem -> left=parent:centerX
otherItems->leftMiddleItem rightMiddleItem<-otherItems
You can also center an invisible placeholder in the center, and anchor to that, but you will still need to consider an odd/even number of items when constraining, so I don't recommend that approach.
You might want to refer this
Percentage based marking
Basically, it says first being with the some incorrect margin and then correct it wrt to its parent view.
Working with my case.

UILabel animated resize side effect

I came across issue where I need to animate height change of UILabel frame or its enclosing view's frame. Label is multiline.
The issue is that given with large text which does not fit initially into label(say it takes 3 lines), then animating the label's height to increase, immediately changing 3 line to 4 and then animating the frame increase.
Opposite effect is when the text fully fit into label(4 lines), then I animate height decrease, 4 lines are instantly becoming 3 and only then I see animating frame size decrease.
This is of course not good for an eye.
What I expect is something like keep the label's origin.y intact and then as frame is increasing the more text is revealing from the bottom. The ellipsis may convert to missing word instantly, that is not a problem.
If you want to keep origin.y intact then you have to animate it with CoreAnimation stuff.
Set once:
label.layer.anchorPoint = CGPointMake(0,0); //I believe 0,0 is the upper left or it was 0,1?
after doing this you just need to change the size accordinly:
I would measure the text first (With NSString's methods)and see if the label needs to be resized.
In case it needs to then adjust label.numberOfLines and label.layer.bounds = CGRectMake(label.layer.bounds.origin.x,label.layer.bounds.origin.y,
label.layer.size.width, newHeight);
This should work
I hope this helps.

Clipping within an UIView with some subviews

I have some buttons in an UIView. My problem is, that they get cut
off at the right side of the UIView. How do I prevent this?
alt text http://img.skitch.com/20090629-mj32p1bkff476256pwrpt69n2d.png
I've checked already Interface Builders clip property, but it's no
solution for this problem.
Regards
It seems like either you made these buttons programmatically, or you reiszed the initial IB view window to be larger and expected it to shrink down to the fit the screen.
The buttons in question cannot fit on the screen as they are - what effect are you looking for?
If you want the buttons all to fit you could set the text size to be smaller, and then they could fit.
If you want the buttons the size they are then you'll have to make another row, or put the buttons into a side scrolling container.
I have been using java and only recently began learning Apple's Obj-C framework.
An alternative to scrolling and row-breaking is using a "grid" layout with 1 row and n columns, where n is the number of buttons. Each cell has a fixed size. And you will have to resize your buttons (the subviews) in your superview's setNeedsLayout: method to whatever width you need such that all buttons fit the row.
See java's GridLayout class.
Kendall, thanks for your answer.
Here is my solution:
if(previousFrame.origin.x + theStringSize.width > 220){
roundedButton.frame = CGRectMake(15, previousFrame.origin.y + 30 , theStringSize.width + 8, theStringSize.height);
[myContainer insertSubview:roundedButton belowSubview:[tagsContainer.subviews lastObject]];
}else {
roundedButton.frame = CGRectMake(previousFrame.origin.x + previousFrame.size.width + 5, previousFrame.origin.y, theStringSize.width + 5, theStringSize.height);
[myContainer insertSubview:roundedButton belowSubview:[tagsContainer.subviews lastObject]];
}
I calculate, how many pixel I've moved from the left side. At some threshold (in my case 220) I start a new line.