Adjust UIView width when other views increase or decrease in size - ios

I have a UIView with a side menu that comes from the left and pushes the right view from full with to a smaller size (full width - (menu width)).
Per someones suggestion I accomplish that effect by changing the constant in the constraint for the menu width: from 0 to 200.
The (right side view) UIView that's gonna hold the view that I will load to it has the constraints seen in this image (menu is on the left in blue):
I add the new UIView to the detailsView (container mentioned above) with the following code:
var viewNames = NSDictionary.FromObjectsAndKeys (new NSObject[] {
view.View
}, new NSObject[] {
new NSString ("detailsView")
});
detailsViewContainer.AddSubview (view.View);
view.View.TranslatesAutoresizingMaskIntoConstraints = false;
detailsViewContainer.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[detailsView]|", 0, new NSDictionary (), viewNames));
The problem is that the newly added view always has the full width (1024) when the menu is collapsed but also when the menu is expanded, pushing the view outside the app limits on the right.
Any help would be appreciated.
Thanks in advance!

Make the master view width constraint (add one if there is no) to be <= 1024 (not strict). I would do the following:
|H:|-0-menuView-masterView-0-|
and specify in designer the width constraint for masterView as Less or Equal 1024
and specify in designer the width constraint for menuView as equal to 200. Make an outlet for it and change dynamically in code with
animation from 200 to 0 and back when required.
where:
menuView is menu UIView
masterView is master UIView placeholder
when your menu (green view) is open width constraint will be equal 200:
as soon as you set constraint to 0 your view will resize the main placeholder (orange view) as well:
Please find storyboard sample by the following link:
https://dl.dropboxusercontent.com/u/19503836/Main.storyboard

Related

iOS - hideable UIView at the top of the screen

I want to create an info view that will show at the top of the screen and disappear after some time, and later it can show again and so on.
I have created UIView and set constraints:
topInfoView.leadingAnchor.constraint(equalTo: mainView.leadingAnchor)
topInfoView.trailingAnchor.constraint(equalTo: smainView.trailingAnchor)
topInfoView.heightAnchor.constraint(equalToConstant: HEIGHT)
Closed state:
topInfoView.topAnchor.constraint(equalTo: mainView.topAnchor, constant: -HEIGHT)
Open state:
topInfoView.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 0)
where mainView is main UIViewCcontroller view.
I set HEIGHT as my user height + "status bar height" (bar with battery, Wifi etc). Problem is, that sometimes status bar height is 0 and my topInfoView is incorrectly placed. I am obtaining "status bar height" via this:
func statusBarHeight() -> CGFloat {
let statusBarSize = UIApplication.shared.statusBarFrame.size
return Swift.min(statusBarSize.width, statusBarSize.height)
}
but it sometimes not works (views are not inited?) and I am also not sure about new iPhone X, where status bar is solved differently. Is there any other way, without calculating the height?
Use the vertical stack view. Put the tableView and then your view vertically one after the another. Set the height of the table view. Keep the distribution property of stack view to fill. Create an outlet of the tableview. With this arrangement when you will hide the tableview, your view will fill the whole area. When you again set isHidden property to false of table view your table view and view will appear as original arrangement. You can animate while hiding and showing table view to give a good user experience.

Xamarin iOS Autolayout: Resize width and vertical scroll automatically for various devices while keeping the horizontal scroll disabled

I want to create a page which has a vertical but no horizontal scroll. It must adjust width of the content and vertical scroll automatically as per screen size.
Something similar to this:
I can not use UITableView since, my page may not have necessarily homogenous elements. It could have a combination of textfields , dropdown etc.
The previous answer was quite right, but not right at all. Indeed I tried to solve this problem using the method described before, but to make it work, I made some adjustments.
Your view's hierarchy has to be as follow :
UIScrollview :
View1
View2
View3
You don't need a container inside the UIScrollview, because apart the fact that it will be an extraview that you don't need, there is the problem that if you use this container-view you will get problem getting touch events in the views added.
So, let's make a step-by-step process:
Add scrollview to your viewController
The first step is to add the scrollview to your viewController, and we can simply do this programmatically in the following way:
UIScrollView scrollView = new UIScrollView();
scrollView.TranslatesAutoresizingMaskIntoConstraints = false;
View.AddSubview(scrollView);
View is the main-view of the viewController you are working in (aka Self.View).
Put attention to set TranslateAutoResizionMaskIntoConstrains property of the scrollview to false, otherwise autoresizing will mess your constraints.
Add constraint (autolayout) to your scrollView
You need to ensure that you layout will adjust for every different iPhone-screen, so simply use auotlayout to pin your scrollView to the viewController main-view (is the View used in the next code sample):
scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor, 0).Active = true;
scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor, 0).Active = true;
scrollView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor, 0).Active = true;
scrollView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor, 0).Active = true;
In this way your scrollView is pinned to the bound of the main-view.
Create the view to be added
You need to create the view that you will add to the scrollView:
UIView viewToBeAdded = new UIView();
viewToBeAdded.TranslatesAutoresizingMaskIntoConstraints = false;
viewToBeAdded.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 200);
We have created a new UIView that setting its frame large as the screen (UIScreen.MainScreen.Bounds.Width) so it won't scroll horizontally, and with an arbitrary height (200 in the sample).
NOTE : even in this case you have to set TranslateAutoResizingMaskProperty to false, otherwise you will get a mess.
Add the view to the scrollView
Next step is to add our new view to the scrollView as follow:
scrollView.AddSubview(view);
Nothing more.
Set constraint for the view added in relation to the scrollView
Once you have added your view you have to said which will her behavior related to the scrollView. We assume that we will add several view to the scrollView, so we have to made a distinction, to the behavior of the FIRST view, the IN-BETWEEN views, and the LAST view.
So to be clear we assume that we are adding only 3 views, so we will have the three different cases.
FIRST VIEW
The important thing is that the first view has to be pinned to the top of the scrollView, we do this as follow :
firstView.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor, 0).Active = true;
and then we set the others constraints:
firstView.WidthAnchor.ConstraintEqualTo(firstView.Bounds.Width).Active = true;
firstView.HeightAnchor.ConstraintEqualTo(firstView.Bounds.Height).Active = true;
IN-BETWEEN VIEW
The in between views (in our sample the secondView) need to be pinned to the previous view added (in our case the first view). So we do as follow:
secondView.TopAnchor.ConstraintEqualTo(firstView.BottomAnchor).Active = true;
So the top of the secondView is pinned to the bottom of the firstView.
And then we add the others constraints:
secondView.WidthAnchor.ConstraintEqualTo(secondView.Bounds.Width).Active = true;
secondView.HeightAnchor.ConstraintEqualTo(secondView.Bounds.Height).Active = true;
LAST VIEW
The last view (in our case the third view) instead needs to be pinned to the bottom of the previousView (in our case the secondView) and to the bottom of the scrollView.
thirdView.TopAnchor.ConstraintEqualTo(secondView.BottomAnchor).Active = true;
thirdView.BottomAnchor.ConstraintEqualTo(scrollView.BottomAnchor).Active = true;
And the usual other constraints for width and eight:
thirdView.WidthAnchor.ConstraintEqualTo(thirdView.Bounds.Width).Active = true;
thirdView.HeightAnchor.ConstraintEqualTo(thirdView.Bounds.Height).Active = true;
In this way the eight of the scrollView will adapt to the eight of the views added, due to the fact that the views inside are pinned to the top and the bottom of the scrollView.
CONCLUSIONS
If you follow these simple instruction you will get everything work. Remember to disable autoResizingMask, as this is on of the common mistake.
Hope it was helpful.
Cheers
In a custom renderer for Xamarin.Forms i've written my UITableViewController like this:
_controller = new InfoFieldItemsTableViewController();
_controller.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
_controller.TableView.SeparatorColor = UIColor.Clear;
_controller.TableView.AllowsSelection = false;
// http://useyourloaf.com/blog/self-sizing-table-view-cells/
_controller.TableView.RowHeight = UITableView.AutomaticDimension;
In my controller i am doing this to register all potential cell candidates:
private void RegisterCells()
{
foreach (var tuple in InfoFieldCellMapping.Map)
{
this.TableView.RegisterNibForCellReuse(tuple.Value.Item1, tuple.Value.Item2);
}
}
public override void ViewDidLoad()
{
RegisterCells();
base.ViewDidLoad();
}
I am doing this in my controller so cells resize themselves depending on how much height they need:
public override nfloat EstimatedHeight(UITableView tableView, NSIndexPath indexPath)
{
return 100;
}
Now all you need to do is create cell files from within your IDE which should be .xib files and design them in the editor using autolayout (so they can adapt to orientation changes automatically).
Within your TableViews datasource all that's left to do is mapping between your data item and it's corresponding cell similar to:
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
var dataItem = Items[indexPath.Row];
var key = ""; // use info from data item to figure out which key identifies your table cell to dequeue the correct kind of cell
var cell = collectionView.DequeueReusableCell(key, indexPath) as UICollectionViewCell;
}
That's all you need really. In my scenario i am mapping fields which may contain different controls for date entries, number entries, long texts, short texts etc etc.
I hope that helps
1.Add Leading,Trailing,Top,Bottom Constraints on scrollView to it'superview.
2.Add UIView as containerView of scrollview and add 6 Constraints from containerView to scrollview as below.
a)Leading b)trailing c)top d)bottom e)Center Horizontally.
3.Make sure top elements in container view must bind to top by adding top constraints and also bind bottom most element to bottom of container view by adding bottom constraints.And also all the items between topmost and bottommost in the container view must be vertically connected to each other so it will define the content size of container view.
it will define the actual content height for scrollview.
and finally define content size for scrollview in code.
As I mentioned here .
Refer to Step 1 and Step 2 ,set constraints on Scrollview and containerView.
I remove the margin between Scrollview and View , and I add some controls on the containerView , so it looks like as below:
Notice
Since we set the containerView's width equal to scrollview's width, the width is fixed, so we can scroll vertically not horizontally.
Height of controls and spaces between them should be set clearly, because the contentSize is auto calculated by adding them. (If contentSize is greater than the height of screen ,the scrollview can be scrolled)
I saw you set those constrains on controls , but you can't scroll down to see the controls out of screen, I think you are missing to set bottom margin on the last control(the downmost one).
Let us do a test.
1. We set the margin (between button and textfield ) to 1000 and don't set bottom margin between the textfield and containerView.
Result : can't scroll down to see the textfield out of screen.
2. Set the margin 1000 and add a bottom margin(10) between textfiled and containerView.
Result: can scroll
Demo Link

Re-position uilabel

I wanted the "number" & "status" to display on the left if there is not QRCode display (constraints has been set for image & labels.)
Result without QRCode:
.
The result with QRCode will be:
IT IS very easy just make width Constraint of QRcode image, if QR code is not available than make widht constant = 0,
#IBOutlet weak var width: NSLayoutConstraint!
if (your condition)
{
width.constant = 0
}
else
{
width.constant = 30
}
You can do that with a second pair of constraints attached to left side of a view.
Add outlets to that constraints and set constant value to desired offset(from code), if there is no QRCode View.
Another way is to add MoreThanOrEquel constraint to left side (e.g >= 10)
Than another constraint with constant value 10, but with lower priority.
When you remove QRCode view, it will destroy it constraints and constraints to left side will affects and move yours labels to left.
You could make constraint for labels that way:
I.e. make constraint for image leading to left side + image width, both labels also have leading to left side. Then if there is no QR Code adjust labels leading constraints to value you need.
Or you could make both labels leading to image view and set the image view width constraint to 0.
This Problem is very simple , can achieve using UIStackView just making hide/Show.
For Ex: If QR-code is present show or else hide QR-Code.
Label (Number and status and image) will automatically get adjust. Following is the screen short for better understanding.
IBOutlet UIView *qr_view; // Image or View
Case 1 :QR Present
qr_view.hidden = NO;// Show
Case 2: QR Not Present
qr_view.hidden = YES;// hide

Swift: Views not adjusting to programmatic constraints

I have a view that I am making hidden at the bottom of the screen, and want the scrollView above it to adjust and fill the void space.
The view at the bottom of the screen is a GADBannerView and has a fixed height of 50 (bannerHeight). The scroll view above it has a constraint to the bottom of the container that equals 50 (scrollConstraint). See photo.
In viewDidLoad is am setting these constraints to the following:
bannerHeight.constant = 0
scrollConstraint.constant = 0
This is causing the bannerView did disappear but the scroll view is staying in it's original position and not filling the void space.
You can force the superview to take into account the change of the constraint because this does not happen automatically. Add your code to viewDidLayoutSubviews() instead or simply call view.layoutIfNeeded() after you set the constants to 0 in the viewDidLoad().
If this does not work, you can try this alternative approach:
Go to your Storyboard and click on the scroll view's bottom constraint (the blue line that gives the scroll view its bottom constraint of 50). In the Attributes Inspector you should be able to see details about your constraint, it should look something like this
In the field that asks for an Identifier, give it the name "ScrollViewBottom" or whatever name you like.
Now loop over all the constraints that make up your scroll view and use the identifier name to find the correct one and change it's constant as follows
for constraint in yourScrollView.superview!.constraints {
if constraint.identifier == "ScrollViewBottom" {
constraint.constant = 0
}
}
Finally, force the view to take into account of this change by calling the following straight after
view.layoutIfNeeded()

Updating constraints programmatically

Situation is like I have a view with four buttons
There comes a condition when button with text Search Community should be hidden and width of Options button should get increased
Using Constraints for the first time in my project, I am not getting how to achieve this. Set of constraints added on both these buttons would be clear from the following two images.
The problem I see with your setup is that you have this constraint between the 2 buttons of equal width. This is true in the first case but when you want to hide one of them, it is not anymore.
So, you will need to rethink your constraints a bit. Maybe instead of the equal width constraint, you could use a static width constraint one the first button(the left one, that you want to hide). Then the second one, will just have a horizontal space constraint to the first one, and a trailing space to the superView.
Then you make an outlet in the VC for the width constraint of the first button and when you want to hide it you do something like this:
self.searchButtonWidthConstraint.constant = 0
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded() // if you want to animate the constraint change
})
Let me know if you have questions. Good luck and hope it works out!
Update
For the landscape use case, you could listen to the orientation change notification, to update the width constraint of the button
-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
self.searchButtonWidthConstraint.constant = LANDSCAPE_WIDTH
UIView.animateWithDuration(duration, animations: { () -> Void in
self.view.layoutIfNeeded() // if you want to animate the constraint change
})
}
Add constraint to 1st Button
Leading Space To NewView(gray colored)
Bottom space to NewView
Top Space to Topbutton (blue colored in your 1st and 2nd image)
Width (from Bottom - Right portion )
Add Constraint to 2nd Button
Trailing Space to NEwView
Bottom space to NewView
Top Space to Topbutton (blue colored in your 1st and 2nd image)
Horizontal space FirstButton ( Search Community )
Width

Resources