Swift4 issues : change Nslayoutconstraint programmatically - ios

I would like to change position of UITextfield txtAmount NSLayoutConstraint programmatically from its top to bottom of collection view to bottom of image view. All views are embed in a ui view.
Old constraint is dragged and mapped from storyboard to view controller.
New constraint constr is to be created programmatically.
When it comes to implementation and execution, it says
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal.
Would you please tell me any guidelines for such modification ? I embed the UI elements in an embedded UIView because of scrollview I have used.
let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)
IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()
txtAmount.addConstraint(constr)
txtAmount.removeConstraint(constraintPo)

you are adding constraint to the txtAmount whereas you should've added it to the view which actually contains txtAmount and another view referenced in this constraint, i.e. imageView. Let's name this view which contains them superview.
let constr = NSLayoutConstraint(item: txtAmount, attribute: .top, relatedBy: .equal, toItem: imageView, attribute: .bottom , multiplier: 1, constant: 0)
IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()
txtAmount.removeConstraint(constraintPo)
superview.addConstraint(constr)
But this is not recommended way since iOS 8. As the docs say, you should set the constraint isActive (read this) property to true instead, and iOS will add them to relevant views:
IETypeList.removeFromSuperview()
uiviewType.removeFromSuperview()
constraintPo.isActive = false
constr.isActive = true

Related

Multiple UILabel at the same line in UIStoryboard

If there are multiple UILabels in one UIStoryboard, and they have the same centerY, which means they are at the same line. How can I use autolayout to let them fit in different screen? I hope these UILabels have same font size.
You need to add constraints. There are a couple of ways to add constraints.
If you go to the storyboard you will see a rectangle in between 2 vertical lines. If you click the the view you want to add constraints too (Like the UIView you added) and click that rectangle box thing It gives you options to add constants to the left, right, top, bottom of the view. If you click on the dropdown menu it gives you a list of views around the view your adding constraints too so that you can add constraints relative to that view.
Another way to add constraints is clicking the triangle button in between 2 vertical lines and selecting the option "add missing constraints". Auto layout will then try and determine the best constraints to add automatically.
To delete or modify constraints you can click the "show size inspector" (looks like a ruler) and in the constraints section you should see some constraints if you have added any. You can click and delete them or edit them.
Another option is adding constraints programmatically (below is an example of adding constraints to an image view in a stack view in swift):
let trailingConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.stackView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -5)
let leadingConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.stackView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5)
self.stackView.addArrangedSubview(imageView)
self.stackView.addConstraint(trailingConstraint)
self.stackView.addConstraint(leadingConstraint)

Xcode swift view wrap content

I'm an Android developer trying my hand at Xcode and it's been unpleasant so far. What I'm trying to do is have a custom view that has three sub views:
UIImageView (for an icon)
UILabel (for the title)
UILabel (for the content)
I want it such that the content label's height grows and shrinks to wrap the text it contains (like Android's wrap_content). And then, I want the custom view to also grow and shrink to wrap all three sub views.
However, I cannot, for the life of me, figure out how these auto layouts/constraints work.
01) How would I make my UILabel's height grow/shrink to match its contained text?
02) How would I make my custom view's height grow/shrink to match its contained sub views?
override func layoutSubviews() {
super.layoutSubviews()
img_icon = UIImageView()
txt_title = UILabel()
txt_content = UILabel()
img_icon.backgroundColor = Palette.white
img_icon.image = icon
txt_title.text = title
txt_title.textAlignment = .Center
txt_title.font = UIFont(name: "Roboto-Bold", size:14)
txt_title.textColor = Palette.txt_heading1
txt_content.text = content
txt_content.textAlignment = .Center
txt_content.font = UIFont(name: "Roboto-Regular", size:12)
txt_content.textColor = Palette.txt_dark
txt_content.numberOfLines = 0
txt_content.preferredMaxLayoutWidth = self.frame.width
txt_content.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.backgroundColor = Palette.white
addSubview(img_icon)
addSubview(txt_title)
addSubview(txt_content)
/*snip img_icon and txt_title constraints*/
let txt_content_x = NSLayoutConstraint(item: txt_content, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)
let txt_content_y = NSLayoutConstraint(item: txt_content, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 80)
let txt_content_w = NSLayoutConstraint(item: txt_content, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0)
let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)
txt_content.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
txt_content_x,
txt_content_y,
txt_content_w,
txt_content_h
])
}
I understand that, in the above code I've tried, I have the height set to a constant 40. This is only because I don't know how to achieve what I want.
[EDIT]
I've tried setting the height constraint to greater than or equal to but it just crashes Xcode.
[EDIT]
It crashes Xcode if I try to view it but works perfectly fine in the simulator. Question now is, why?
My height constraint is now:
let txt_content_h = NSLayoutConstraint(item: txt_content, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40)
It works in the simulator and has the desired behaviour. However, if I open the storyboard that contains the view, it crashes. It's definitely that line of code because changing it back to .Equal resolves the crash.
[EDIT]
My temporary fix is:
#if TARGET_INTERFACE_BUILDER
//use .Equal for height constraint
#else
//use .GreaterThanOrEqual for height constraint
#endif
This way, it doesn't crash Xcode and still renders the way I want it on the simulator.
[EDIT]
I removed the pre-processor check because I realized there's no actual thing like that defined and it still works now. I swear I've changed nothing else.
I am this close to giving up on iOS development because the interface builder keeps crashing Xcode without a reason when everything works in the simulator. Then, I do some nonsense edits and it works fine again.
01) How would I make my UILabel's height grow/shrink to match its contained text?
Just set top, left and right-constraint to the labels superview. Set the property number of lines to 0. Then it will start wrapping text.
02) How would I make my custom view's height grow/shrink to match its contained sub views?
By using interface builder this is much easier to achieve.
My suggestion to you is to start with your constraints in storyboard. You will not need to compile your code to see what the constraints will result in. Also you will get warnings and errors directly in the interface builder.
If you WANT to use programmatic constraints, my suggestion is to start using a framework for it. For example: https://github.com/SnapKit/SnapKit
You can use a trick with constraints to achieve wrap-content. For example :
let maximumWidth = frame / 4 //For example
yourView.widthAnchor.constraint(lessThanOrEqualToConstant: maximumWidth).isActive = true
The "maximumWidth" depends on your UI and your design and you can change it.
Also, you should set "lineBreakMode" in StoryBoard or in code like :
yourBtn.titleLabel?.lineBreakMode = .byCharWrapping //For UIButton or
yourTxt.textContainer.lineBreakMode = .byCharWrapping //For UITextView
Often clean will do a lot of good when code jams for no reason ar all, cmd-shift-k if i remember correctly
I understand there is no direct application of wrap content in iOS just like we have in Android and thats a big problem, I resolved it through manual anchors like this.
create a function with where in you calculate the height of the view using
mainView.contentSize.height
and then set anchors based on the total height to the enclosing view, call this function inside
override func viewWillLayoutSubviews()
And this would work, the viewWillLayoutSubviews() is a lifecycle method and whenever you override you have to do
super.viewWillLayoutSubviews()
This worked in my case, might work with yours too, if there is a better approach please do comment.

How to setup layout constraints for a horizontal alignment of UIImageView's

I am trying to implement something like the image shown (http://i.stack.imgur.com/jKmGO.png) below using auto layout in Swift, but every time I end up with some issues. Can anyone please tell me the best way to implement auto layout for this kind of arrangement in horizontal grid for 3,4,5 or more image views.
Try the following steps
1) first select all of them and add constraint EQUAL WIDTH to images
2) set the leading space between left margin and first image view( let it be d)
3) Similarly set trailing space between the right margin and last imageview (let it be d)
4) Now add constraint HORIZONTAL DISTANCE(d) between all the image view e.g.
LEFT MARGIN-d-IMAGE1-d-IMAGE2-d-IMAGE3-d-IMAGE4-d-RIGHT MARGIN
Checkout Stanford Cs193p lecture no 8. Something similar is considered which was a basic calculator with equal width and height of keys.
Try code below (for horizontal arrangement)
var arrayOfImages = [image1,image2,image3,image4]
var previousImage:UIView? = nil
let horizontalSpaceBetweenImages = 20.0
let viewToUse = self.view //change this view to the one in which you are adding images as subviews
for image in arrayOfImages {
viewToUse.addSubview(image)
if previousItem == nil {
// this is the first item
viewToUse.addConstraint(NSLayoutConstraint(item: viewToUse, attribute: .Leading, relatedBy: .Equal, toItem: image, attribute: .Leading, multiplier: 1.0, constant: 0.0))
}
else {
viewToUse.addConstraint(NSLayoutConstraint(item: image, attribute: .Leading, relatedBy: .Equal, toItem: previousImage, attribute: .Trailing, multiplier: 1.0, constant: horizontalSpaceBetweenImages))
viewToUse.addConstraint(NSLayoutConstraint(item: image, attribute: .Width, relatedBy: .Equal, toItem: previousImage, attribute: .Width, multiplier: 1.0, constant: 0.0))
}
previousImage = image
}
// now add trailing constraint for last image
viewToUse.addConstraint(NSLayoutConstraint(item: arrayOfImages.last, attribute: .Trailing, relatedBy: .Equal, toItem: viewToUse, attribute: .Trailing, multiplier: 1.0, constant: 0.0))
this code sorts out horizontal alignment. It should be trivial to then add vertical alignment constraints (they should be easier to implement)
A collectionView would be the best option for you if you are going to be switching between 3, 4, and 5 images in your view. If you are, however, trying to have a set number of images displaying (number of UIImages stays the same) You can try doing this method:
Everything here is going to be based on the horizontal distance available to you based on the device size. So to start, you need to figure out what height you'll want for the images. Do the heights need to be relative to the width? Or can the heights for each image stay the same?
If the heights need to stay relative to the widths, put an "Aspect Ratio" constraint on each image. If the heights can stay static, place a "height constraint" on each image.
Next you need to set constraints for the distances between the images.
At this point you are still going to have errors because the width for each image will be ambiguous. To fix this, select all the images simultaneously and then add the constraint "Equal Widths." As long as you've made sure that the images are pinned to the top, you should no longer have auto-layout issues at this point.
Let me know if I can be more clear on any of these steps.

What is the difference between Top and TopMargin in NSLayoutAttribute?

I am trying to create a constraint via code:
constraintImageCharacterTop = NSLayoutConstraint (item: image,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: viewTop)
self.view.addConstraint(constraintImageCharacterTop)
However, I am not sure which is the right NSLayoutAttribute for this constraint. image should have a top space to the main Superview self.view.
This is how I think it works, but I am not sure if I am correct:
Should I use NSLayoutAttribute.Top or NSLayoutAttribute.TopMargin for image A?
I usually don't use constraint to margin, it is a personal preference, either to constraint to the edge of the view or to constrain to its margin (8px). Let's say your Image A has a top of 8px, you could create a top constraint with a constant of 8, or a top margin constraint with a constant of 0, you will get the same result.

Auto Layout left margin constraint based on percentage of screen width

I have 4 buttons. I want them to be 13% of the screen width from the left edge and bottom edge. I'm using Auto Layout and Size Classes. I know I can specify a number of points in Interface Builder with Storyboards but obviously this won't get the job done when going from device to device. Do I need to hook up a constraint through an IBOutlet and calculate the constraint there in code to achieve the desired result? Or is this possible using Interface Builder?
This is special case, which can't be handled in IB (AFAIK). These combo boxes don't contain all available attributes.
Do it in code:
let con = NSLayoutConstraint(item: myView, attribute: .Left, relatedBy: .Equal,
toItem: fullWidthView, attribute: .Width, multiplier: 0.13, constant: 0.0)
Replace myView with your button. Replace fullWidthView with any view which occupies whole width of the device. Typically UIViewController.view.
And do the same thing with .Bottom, .Height and fullHeightView.

Resources