How to stick UIButton to the bottom of UIScrollView? (Chatto framework) - ios

I want to create such a UI that have two buttons stick to the bottom of the screen and a UIScrollView above them. I am using Chatto framework and would be great if anyone could give me an example how to do that based on https://github.com/badoo/Chatto/tree/master/ChattoApp/ChattoApp.
Here is the visualization of view that I'd like to have.

there is a better solution for this. you can do this by disabling the Auto Layout(button.translatesAutoresizingMaskIntoConstraints = false) property of the corresponding Button or any UIView for floating button:
Swift 4 example
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
button.rightAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true
button.bottomAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true
} else {
button.rightAnchor.constraint(equalTo: tableView.layoutMarginsGuide.rightAnchor, constant: 0).isActive = true
button.bottomAnchor.constraint(equalTo: tableView.layoutMarginsGuide.bottomAnchor, constant: -10).isActive = true
}

You can easily do this using constraints. If you're using storyboard, you can set the constraints up using their "Pin" and "Align" features. If you're building it in code, you'll want to programmatically set up your constraints. Just be sure to add all the necessary constraints to fully define how the view should appear.
pseudo example with just one button:
let button = UIButton()
self.view.addsubview(button)
// pin button to bottom of superview,
let buttonBottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
self.addConstraint(buttonBottomConstraint)
// left of superview,
// right of superview,
// and height
let scrollView = UIScrollView()
self.view.addsubview(scrollView)
// and bottom edge to top edge of button
let scrollViewBottomConstraint = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: button, attribute: .Top, multiplier: 1.0, constant: 0.0)
self.addConstraint(scrollViewBottomConstraint)
// left of superview,
// right of superview,
// pin scrollview to top of superview,

Add a full screen scrollview then add a UIView across the bottom (anchoring to bottom of screen). Then add the 2 buttons to the UIView.
If you want to make it semi transparent then make the UIView background color to be clearColor and then add a UIView with alpha of say 0.6 and add this to your original UIView above the buttons.

Related

Constraints not updating and view is letterboxed when rotating device

Background:
When rotating the device, the view myView becomes letterboxed instead of resizing to fit the screen, see image below.
On the storyboard, centreX and centreY constraints are set.
In the code, width and height constraints are set with the function viewAddConstraints(), see code below.
After the device is rotated, I call viewAddConstraints() again, but Xcode gives the following error: Unable to simultaneously satisfy constraints.
Questions:
How do I correctly remove old constraints and then add new constraints when the device is rotated?
How do I correctly update the constraints of a view when the device is rotated?
Code:
func viewAddConstraints() {
// Width constraint full width of screen
let myViewWidth = NSLayoutConstraint(item: myView as Any, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.bounds.width)
myView.addConstraint(myViewWidth)
// Height constraint full height of screen
let myViewHeight = NSLayoutConstraint(item: myView as Any, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.bounds.height)
myView.addConstraint(myViewHeight)
}
Image:
Current situation, view is incorrectly letterboxed.
Intended situation, view resized correctly.
The proper way to set constraints to keep your subview "pinned" to the sides:
override func viewDidLoad() {
super.viewDidLoad()
let myView = UIView()
myView.backgroundColor = .systemTeal
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
NSLayoutConstraint.activate([
myView.topAnchor.constraint(equalTo: view.topAnchor),
myView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
myView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
myView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
Or, since you should be respecting the Safe Area:
override func viewDidLoad() {
super.viewDidLoad()
let myView = UIView()
myView.backgroundColor = .systemTeal
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
myView.topAnchor.constraint(equalTo: g.topAnchor),
myView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
myView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
myView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
}
Now your subview will automatically resize to fit its superview on device rotation.

Swift insert big height label into view

I'm new to the Swift and trying to add label programmatically to UIView which is embedded into scroll view.
Actually, i want to have something with header (picture and title for half of the screen) and content below (text with unknown length and images).
I'm added a view container and depending on content i want to add label or image view.
Most of the time it will be like that:
text
image
text
image
and so on.
Add label code (Swift 4):
let label = UILabel()
label.numberOfLines = 0
label.text = blogItem.text
containerView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0).isActive = true
The problem is that text is truncated, when comes to the end of the screen and no scrolling at all.
How can i add bottom constraint correctly (i believe that's all happens because of it?) to make expected behaviour?
Make sure you created a proper hierarchy for working UIScrollView:
Add a scrollView to the hierarchy and use autolayout to properly layout it, e.g., if it is supposed to cover the whole view of the viewController:
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
])
Then you need to add a contentView to the scrollView and provide a proper layout constraints for it, so if you want vertically scrollable scrollView in the example I started above, you need following autolayout constraints:
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// horizontal anchors of contentView are constrained to scrollView superview
// to prevent it from scrolling horizontally
contentView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
contentView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
// but vertical anchors of contentView are constrained to
// scrollView to allow scrolling
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
])
Notice here that I constrained the leftAnchor and rightAnchor of the contentView to the self.view rather than to scrollView to make it of fixed width. However, top and bottom anchors are constrained to the scrollView, so they are expanded and scrollable when contentView needs more space.
Now you add to the contentView all the content that you want, and you lay it out using autolayout as if the contentView was a view with infinite height - scrollView will take care of presenting it whole by scrolling. So in my example if the only content would be one huge UILabel with many lines (label is a subview of contentView):
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leftAnchor.constraint(equalTo: contentView.leftAnchor),
label.rightAnchor.constraint(equalTo: contentView.rightAnchor),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
Try to go over your code and check your constraints. It might be that you miss constraints in both cases, and the fact that it works in first case is just a coincidence.

How to add constraint with dynamic width programmatically [duplicate]

This question already has answers here:
How to add constraints programmatically using Swift
(19 answers)
Closed 6 years ago.
I'm new to iOS development. I want to build layout without storyboard or xib/nib. So I am trying to add constraints programmatically.
I have searched some tutorials about add constraints programmatically. But the view can't show correctly.
I'm trying this code in my ViewController class:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let testView = UIView()
self.view.addSubview(testView)
// Add Constraints
self.view.translatesAutoresizingMaskIntoConstraints = false
testView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal
, toItem: self.view, attribute: .top, multiplier: 1, constant: 50.0)
let bottom = NSLayoutConstraint(item: testView, attribute: .bottom, relatedBy: .equal
, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -50.0)
let leading = NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
let trailing = NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -50.0)
self.view.addConstraints([top, bottom, leading, trailing])
}
Generally, they don't need to define the size of view or constraints about width and height in tutorials. But the views can be shown on their tutorial. In my case, my testView can't show it in the app even top, bottom, leading and trailing constraints have been set. Am I missed something? What's the problem?
one of the tutorials:
http://www.knowstack.com/swift-nslayoutconstraint-programatically-sample-code/
Edit:
Let's me explain more. I want to create a UIView that suitable for universal device. The UIView has top, bottom, leading and trailing constraints with constant: 10. So, I don't need to set size of UIView.
Expected Result (I am using draw tool to simulate the result)
This is an example of a view constraint to the bottom of the screen with height equal to 80:
var yourView = UIView()
yourView.translateAutoresizingMaskIntoConstraints = false
yourSuperView.addSubview(yourView)
// Pin the leading edge of yourView to the leading edge of the main view
yourView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
// Pin the trailing edge of yourView to the leading trailing edge
yourView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
// Pin the bottomedge of yourView to the margin's leading edge
yourView .bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
// The height of your view
yourView.heightAnchor.constraintEqualToConstant(80).active = true
You have two issues:
Do not set self.view.translatesAutoresizingMaskIntoConstraints = false. You only need to set translatesAutoresizingMaskIntoConstraints for the subview you are adding.
You are using .greaterThanOrEqual constraints instead of .equal constraints. The problem with that is that leaves a lot of wiggle room and you are getting values that cause your testView to have 0 width. If you change to .equal that will properly constrain the values.

Add Constraint to navigationBar Programmatically Swift

I'm trying to add constraint to navigation bar, I have UIImageView, which has width, height and is centered horizontally, I want to add vertical space between UIImage and navigationBar to 0, I'm trying this for like 1 hour and couldn't figure out how, i tried adding constraint to UIView, and added constant of navbarHeight + statusBarHeight, and it worked, but I want to make relationship between imageview and navbar
let verticalSpace = NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)
view.addConstraint(verticalSpace) // this works
try with topLayoutGuide
let verticalSpace = NSLayoutConstraint(item: image,
attribute: .Top,
relatedBy: .Equal,
toItem: self.topLayoutGuide,
attribute: .Bottom,
multiplier: 1, constant: 0)
The above constraint explanation:
simply its called: vertical space between image.Top & self.topLayoutGuide.Bottom = 0
that means Top constraint of image view attached with a Bottom attribute of topLayoutGuide with constant 0.
You can use anchors as well to make this possible for iOS 10+
if #available(iOS 11.0, *) {
image.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
} else {
image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
llkenny's answer for iOS 11.0+ :
image.topAnchor.constraint(equalTo:
view.safeAreaLayoutGuide.topAnchor).isActive = true
With anchors:
image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
In storyboard. Two constraints:
The first:
The second:
Result:
code:
func mainCollectionViewConstraint() {
NSLayoutConstraint.activate([
mainCollectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
mainCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mainCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
mainCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}

Badge view how to create with a full auto layout approach

It's been a while since I'm trying to create a custom view that has at the top right corner a simple badge.
The custom view is composed by 3 part.
In red there is the custom view itself, that contains:
in blue the container view
in green the badge view a simple UILabel
Container view and the badge view are sibling.
At the moment the container view contains a UIImageView
That view must fit those requirements:
Full auto layout approach
Made programmatically
The custom view must be aligned only considering the blue frame(the container view)
Why that? imagine that you need to position that view by aligning the top edge to the top edge of another view or button, wouldn't be nice if the only the content showed int he container is taken into account?
Here you can see how I set the constraints. The label is placed at the top right corner of the container view.
func setUpConstraint() {
var horContraints = [NSLayoutConstraint]()
horContraints.append(NSLayoutConstraint(item: containerView, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0))
horContraints.append(NSLayoutConstraint(item: containerView, attribute: .Trailing, relatedBy: .Equal, toItem: badge, attribute: .CenterX, multiplier: 1, constant: 0))
horContraints.append(NSLayoutConstraint(item: badge, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0))
var verContraints = [NSLayoutConstraint]()
verContraints.append(NSLayoutConstraint(item: containerView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0))
verContraints.append(NSLayoutConstraint(item: containerView, attribute: .Top, relatedBy: .Equal, toItem: badge, attribute: .CenterY, multiplier: 1, constant: 0))
verContraints.append(NSLayoutConstraint(item: badge, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0))
addConstraints(verContraints + horContraints)
containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Height, relatedBy: .Equal, toItem: containerView, attribute: .Width, multiplier: 1, constant: 0))
}
The container view has also an aspect ratio constraint to keep a square size.
As you can see from the picture everything seems to be fine, except for the fact that when I try to constraint the custom view to the center of its superview, it seems misaligned, because I want the view to be centered respect to the container view (the one with the image). The badge is a kind of decoration such as a shadow and I don't want it to be consider.
To align it correctly I'm trying to override the alignment rect by adding an insets that would "cut" half the label size.
override func alignmentRectInsets() -> UIEdgeInsets {
let badgeSize = badge.bounds.size
return UIEdgeInsets(top: badgeSize.height / 2, left: 0, bottom: 0, right: badgeSize.width / 2)
}
I tried also different configurations but I never was able to fit in the wanted position
If I try to use the other 2 methods alignmentRectForFrame and frameForAlignmentRect (deleting alignmentRectInsets) they are never be called.
Here is what I'd like to obtain:
I've created a little sample code
If the problem is that you want the other view (the "content view", showing the image) to be centered in the ultimate superview, then simply make centering constraints (center x to center x, center y to center y) between the superview and the content view. No law says that a constraint has to be between a view and its direct superview; you can make constraints between any pair of views (that is one of the wonderful things about constraints).
I made a quick mock-up that looks a lot like your "here's what I'd like to obtain" image:
As you can see, Moe (the middle Pep Boy, in the middle of the image) is exactly centered in the superview (shown by the green lines).
For simplicity, the entire interface is created in code, so that I can show you the whole thing. Here it is:
// create the custom view
let customView = UIView()
customView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(customView)
customView.backgroundColor = UIColor.redColor()
NSLayoutConstraint.activateConstraints([
customView.widthAnchor.constraintEqualToConstant(100),
customView.heightAnchor.constraintEqualToConstant(100),
])
// add the content view (image) to the custom view
let contentView = UIImageView(image: UIImage(named:"pep.jpg")!)
contentView.translatesAutoresizingMaskIntoConstraints = false
customView.addSubview(contentView)
NSLayoutConstraint.activateConstraints([
contentView.leadingAnchor.constraintEqualToAnchor(customView.leadingAnchor),
contentView.bottomAnchor.constraintEqualToAnchor(customView.bottomAnchor),
contentView.heightAnchor.constraintEqualToAnchor(customView.heightAnchor, constant: -10),
contentView.widthAnchor.constraintEqualToAnchor(customView.widthAnchor, constant: -10)
])
// add the badge (label) to the custom view
let badge = UILabel()
badge.translatesAutoresizingMaskIntoConstraints = false
customView.addSubview(badge)
badge.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.5)
badge.font = UIFont(name: "GillSans", size: 14)
badge.textAlignment = .Center
badge.text = "567"
NSLayoutConstraint.activateConstraints([
badge.centerXAnchor.constraintEqualToAnchor(contentView.trailingAnchor),
badge.centerYAnchor.constraintEqualToAnchor(contentView.topAnchor),
])
// position the whole thing with respect to the content view
NSLayoutConstraint.activateConstraints([
contentView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor),
contentView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor),
])
But this is not a complete answer to your question. You should now be asking: Yes, but what went wrong when I tried to use the alignmentRectInsets? The answer is: you forgot that the alignmentRectInsets affect alignment with internal views as well as external views. In other words, you certainly can use that approach instead, but then you must adjust the position of the content view accordingly.
So, here's a rewrite in which I use the alignmentRectInsets. First, I'll define a custom view subclass for our custom view:
class AlignedView : UIView {
override func alignmentRectInsets() -> UIEdgeInsets {
return UIEdgeInsetsMake(10, 0, 0, 10)
}
}
Now here's the rewrite. I've put a star (*) next to all the lines that have changed from the previous example:
// create the custom view
let customView = AlignedView() // *
customView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(customView)
customView.backgroundColor = UIColor.redColor()
NSLayoutConstraint.activateConstraints([
customView.widthAnchor.constraintEqualToConstant(100),
customView.heightAnchor.constraintEqualToConstant(100),
])
// add the content view (image) to the custom view
let contentView = UIImageView(image: UIImage(named:"pep.jpg")!)
contentView.translatesAutoresizingMaskIntoConstraints = false
customView.addSubview(contentView)
NSLayoutConstraint.activateConstraints([
contentView.leadingAnchor.constraintEqualToAnchor(customView.leadingAnchor),
contentView.bottomAnchor.constraintEqualToAnchor(customView.bottomAnchor),
contentView.heightAnchor.constraintEqualToAnchor(customView.heightAnchor), // *
contentView.widthAnchor.constraintEqualToAnchor(customView.widthAnchor) // *
])
// add the badge (label) to the custom view
let badge = UILabel()
badge.translatesAutoresizingMaskIntoConstraints = false
customView.addSubview(badge)
badge.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.5)
badge.font = UIFont(name: "GillSans", size: 14)
badge.textAlignment = .Center
badge.text = "567"
NSLayoutConstraint.activateConstraints([
badge.centerXAnchor.constraintEqualToAnchor(contentView.trailingAnchor),
badge.centerYAnchor.constraintEqualToAnchor(contentView.topAnchor),
])
// position the whole thing with respect to the custom view
NSLayoutConstraint.activateConstraints([
customView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor), // *
customView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor), // *
])
That gives exactly the same visual result as before.

Resources