ios using constraints to hide a view - ios

Why is it that if I have a simple viewcontroller with a button, a "control view" and a tableview below it, I can't get the logic to work that will expand the tableview to cover the "view" when the button is pressed and then restore if pressed again. The table will overlay the "control view" but when pressed a second time, does not "restore" the table below the "control view"
#IBAction func buttonPressed(_ sender: Any) {
if bControlHide == false {
myTableView.translatesAutoresizingMaskIntoConstraints = false
myControlView.translatesAutoresizingMaskIntoConstraints = false
myTableView.topAnchor.constraint(
equalTo: myControlView.topAnchor).isActive = true
bControlHide = true
}
else {
bControlHide = false
myTableView.translatesAutoresizingMaskIntoConstraints = false
myControlView.translatesAutoresizingMaskIntoConstraints = false
myTableView.topAnchor.constraint(
equalTo: myControlView.bottomAnchor).isActive = true
}
}

If your controlView has fixed height,
1) Make an outlet for the controlView height from storyboard to ViewController and set it to 0 when you need to hide it. Set another value when you unhide.
Do not forget to set 0 controlView bottom space to tableView, otherwise tableView will not cover your controlView.

You should set the height of tableview and also tableview should be constrained to top and bottom vertical spacing(if you want to support different devices).
Initial setup would be:
height constant is greater than 0
height priority is 1000
bottom constraint is 0
bottom priority is 750
When you tap to button you just need to change priorities:
height priority is 750
bottom priority is 1000

Please pay attention to the following codes:
myTableView.topAnchor.constraint(equalTo:myControlView.topAnchor).isActive = true
myTableView.topAnchor.constraint(equalTo: myControlView.bottomAnchor).isActive = true
Every time you call myTableView.topAnchor.constraint will add a new constraint, this is not what you want.
So please create and save the two constraints to member variables, and then activate or deactivate it according to your needs.
BTW, you don't have to set translatesAutoresizingMaskIntoConstraints every time when you click button, set it once in xib or in viewDidLoad

Related

UISplitViewController - Expand & Collapse Master View in iPad Portrait

My universal app displays both master and detail views in iPad with preferredDisplayMode = .allVisible. I need to expand the master view into full screen and hide the detail view on a button click. I know there is functionality to expand detail into full screen hiding master. But couldn't find how to expand and collapse master view.
I tried in expand function as below.
self.splitViewController.preferredPrimaryColumnWidthFraction = 1.0
self.splitViewController.maximumPrimaryColumnWidth = self.splitViewController.view.bounds.size.width as! CGFloat
And collapse function as below.
self.splitViewController.preferredDisplayMode = .allVisible
self.splitViewController.preferredPrimaryColumnWidthFraction = 0.6
self.splitViewController.maximumPrimaryColumnWidth = self.splitViewController.view.bounds.size.width as! CGFloat
But they don't work. Any ideas on how to achieve this?
My setup uses a navigation bar, but the show/hide functionality would probably work without it. What I wanted to achieve is to have the user decide whether to show the "primary" view and have it shown no matter the orientation - something a UISplitViewController doesn't natively do.
I achieved this through activating/deactivating two arrays of constraints, pinning the secondary" view's leading anchor to the "primary's" trailing anchor. From there, all the constraint changes are with the "primary" view.
(I'm using quotation marks because these view's actually have much more logic that a UIView should have, so they are each UIViewControllers with one being a child of the other, but the constraints are view-related.)
Let's start with the static constraints:
primary.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
primary.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
primary.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
secondary.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
secondary.leadingAnchor.constraint(equalTo: toolBar.trailingAnchor).isActive = true
secondaary.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
secondary.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
Next, define/populate the two arrays that will show/hide the primary:
var isShowingPrimary = false
var showPrimary = [NSLayoutConstraint]()
var hidePrimary = [NSLayoutConstraint]()
showPrimary.append(primary.widthAnchor.constraint(equalToConstant: 300))
hidePrimary.append(primary.widthAnchor.constraint(equalToConstant: 0))
NSLayoutConstraint.activate(hidePrimary)
Notice that isActive is true for the static constraints, and I activated the hidePrimary constraints only.
Now all you need to do is wire up a UIBarButtonItem or UIButton to execute a toggle function that will show/hide the primary view, along with animating it:
func togglePrimary() {
if isShowingPrimary {
// hide primary view
NSLayoutConstraint.deactivate(showPrimary)
NSLayoutConstraint.activate(hidePrimary)
} else {
// show primary view
NSLayoutConstraint.deactivate(hidePrimary)
NSLayoutConstraint.activate(showPrimary)
}
// toggle flag and animate changes
isShowingPrimary.toggle()
UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }
}

How do I limit the size of a UIView in a storyboard designer and the runtime view overall?

I have a custom UIView that's my little component lets call it PlaceholderView.
My UITableViewCell prototype has a Label and a PlaceholderView that sits inside a UIStackView that's vertically axis.
The PlaceholderView, is supposed to call some custom code that goes to a cache to retrieve a specific view then it adds it to the SubView of the PlaceholderView.
I want this subview to take up the whole surface of the entire PlaceholderView. How do I go about doing that? I tried this but not sure if it does the job
if (view != null)
{
AddSubview(view);
view.SizeToFit();
}
Second question. These view's that I am adding, when I create them during design time, I make a new storyboard, drag and drop a ViewController then proceed to place other controls like Labels and Button's on it.
How do I restrict this ViewController's overall height so it's completely fixed size? I know I can set the simulated metrics, and I am also setting the View. Frame's size to restrict the height.
Are there better ways to make these views constrained easier?
Currently, when I am setting these fixed height values, it does cause some weird issues with overlaps if I set UITableView.RowHeigh to AutomaticDimension.
// attaches all sides of the child to its parent view
extension UIView {
func layoutToSuperview() {
guard let view = self.superview else {return}
self.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
self.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
self.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
}
}
Usage:
Instead of view.SizeToFit() use view.layoutToSuperview()
I want this subview to take up the whole surface of the entire
PlaceholderView
You can try autolayout:
if (view != null)
{
view.TranslatesAutoresizingMaskIntoConstraints = false;
AddSubview(view);
view.LeadingAnchor.ConstraintEqualTo(this.LeadingAnchor).Active = true;
view.TopAnchor.ConstraintEqualTo(this.TopAnchor).Active = true;
view.TrailingAnchor.ConstraintEqualTo(this.TrailingAnchor).Active = true;
view.BottomAnchor.ConstraintEqualTo(this.BottomAnchor).Active = true;
}
Are there better ways to make these views constrained easier?
The answer is also auto layout. Set a control's height constraint to claim how much space it wants to take. See this thread for more details: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights.
Though it is native oc, you can see its concept.

Adding and removing UIStackViews messing up my UIScrollView

Whenever I use the pickerview to switch views from Auto Rent to Schedule Rent it works perfectly. It is when I switch from Schedule Rent to Auto Rent that this black bar appears. I have attached the hierarchy of my content view. I thought it had to do with previous constraints added, so I remove a StackView whenever one view is chosen. For example, if Auto Rent is chosen, then I remove the StackView where the Schedule View is in:
//Holds Temp Stackviews
var stackViewHolder1: UIView?
var stackViewHolder2: UIView?
override func viewDidLoad() {
super.viewDidLoad()
stackViewHolder1 = stackViewMain.arrangedSubviews[0]
stackViewHolder2 = stackViewMain.arrangedSubviews[1]
}
if txtRentType.text == "Auto Rent" {
let tempView = stackViewHolder1
let tempView1 = stackViewHolder2
tempView!.isHidden = true
stackViewMain.removeArrangedSubview(tempView!)
if(tempView1!.isHidden == true){
tempView1!.isHidden = false
stackViewMain.addArrangedSubview(tempView1!)
}
else{
let tempView = stackViewHolder1
let tempView1 = stackViewHolder2
tempView1!.isHidden = true
stackViewMain.removeArrangedSubview(tempView1!)
if(tempView!.isHidden == true){
tempView!.isHidden = false
stackViewMain.addArrangedSubview(tempView!)
}
}
I have tried deleting one view and toggling only one view has being hidden and that removes the black bar issue. There is no constraint with the stackViews and Content View.
EDIT:
The screen highlighted is the scrollView. The one after is the contentView. UIWindow goes black in the back.
My Title Bar at the top ends up in the middle somehow.
You can try to modify your stack distribution property
stack.distribution = .equalCentering
After you won't need to use this:
.removeArrangedSubview()
.addArrangedSubview()
When you hide some view, the other view take all space of your stack, you don't need to update your constraints. You can try it on interface builder to see how it works.
are you pinning your scrollview and the content view to the bottom with constraints?
If the content view is a stack view you can pin it to the bottom as well with layout constraints and play with the content distribution.
You don't need to use remove/Add arranged subviews.
when hiding a view in a stackView its automatically removed.
so i think you can just hide or show the stackViewMain.subviews[0] o stackViewMain.subviews[1]
i'm with objc maybe i do a mistake but it would be something like this :
if txtRentType.text == "Auto Rent" {
stackViewMain.arrangedSubviews[0].isHidden = true;
stackViewMain.arrangedSubviews[1].isHidden = false;
}else{
stackViewMain.arrangedSubviews[1].isHidden = true;
stackViewMain.arrangedSubviews[0].isHidden = false;
}

How to modify view controller after pressing a button?

Let's say that if you press the button from the bottom of the screen after typing something in the account text field, you would be required to also enter the password like in the second image.
How should I do this? I don't think that creating a new view controller would be good. So, should I somehow modify the same view controller?
How could I add the new password text field under the account text field?
Keep in mind that they are still centered. Hiding and unhiding wouldn't work in this case and I also need to modify more things than only adding that text field.
First, create a UIView with everything you need on them. in this example I will have only two text fields and they are all color coded.
The view needs to be centered both horizontally and vertically, with width and height. Set identifiler for the height constraint to be updated later. Set the clip to board to true so that when we redeuce the height of the view, text fields below will hide. The settings for the view will be like this
For your text fields, they must have a constant padding to top. In my example, they are set to be in center horizontally, having a constant height, width and padding to opp.
Now, all you need to do is to get the height of the view from code and set the height to show or hide the text fields.
var flag = true
#IBAction func click(_ sender: Any) {
if flag {
flag = false
let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
if let heightConstraint = filteredConstraints.first {
heightConstraint.constant = 60
}
} else {
flag = true
let filteredConstraints = theView.constraints.filter { $0.identifier == "viewHeight" }
if let heightConstraint = filteredConstraints.first {
heightConstraint.constant = 128
}
}
}
Here is the code running in simulater.
another option is you can make tableView at Center, you need to create tableview height constraint outlet,
then you can maintain a counter how many time you want to add View, the counter should be return in tableView numberOfRowsInSection,
and you can make this view in Prototype Cell or using NIB, then just adjust header label text, textField placeholder and text on specific cell index,
when you increase or decrease counter update tableView Constraint, example you have a cell height as 50, in first case when you have on cell in tableView, you can set your tableView height constraint's constant as 50, when cells are two the 100 and so on.....
I think it's a simple logic

Auto Layout how to move the view2 from right to the bottom?

I have two views in the cell at the left UIImageView and at the right UIView Containing some other views as in picture
Now I want if the width of Cell is => 300 then View2 should be at the right of Screen as it is in picture other wise it should be moved to the bottom of View1
Do one thing. Set another constraints for that view
1) leading to main view
2) top to imageview (you can give this constraint by right click from view to drag imageview then vertical spacing.)
Now give outlets for this two constraints programatically.
And also give outlets for constraints which are:
1) leading from view to imageview
2) top of view.
Now as per your requirement,set if condition
e.g.
if(width => 300)
{
topOfViewToImageviewConstraint.isActive = false
leadingOfViewToMainViewConstraint.isActive = false
}
else
{
leadingOfViewToImageViewConstraint.isActive = false
topOfviewToMainView.isActive = false
leadingOfViewToMainViewConstraint.constant = 0
topOfViewToImageviewConstraint.constant = 20
}
This will work. I am not currently in Xcode, so this is just some sample code, but the idea will work.
in cellForRowAt
check if self.tableView.cellForRowAt(IndexPath.row).frame.width => 300
if it is, make no change, but if it is not find the y coordinate of the bottom of view 1 and make a new rect at (x: 0, y: botOfView1, width, height). Then set the frame of view 2 equal to that.

Resources