safeAreaLayoutGuide to my inputAccesoryView - ios

So with the new iPhone X, some things in my app are in the wrong position. In the bottom of my app, i have an accesoryView, which is basically an UIView with a textfield and other elements. I saw something about safeAreaLayoutGuide in the new iPhone X, but i do not now how to implement in the accessoryView. So i'm trying to find a code to implement it in my app, so the safeArea does not bother me anymore.
This is the code for the inputAccesoryView
lazy var inputContainerView: UIView = {
let containerView = UIView()
containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.backgroundColor = UIColor.white
containerView.addSubview(self.inputTextField)
containerView.addSubview(self.swiche)
containerView.addSubview(self.separatorLineView)
containerView.addSubview(self.uploadImageView)
//x,y,w,h
self.inputTextField.leftAnchor.constraint(equalTo: self.swiche.rightAnchor, constant: 4).isActive = true
self.inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
self.inputTextField.rightAnchor.constraint(equalTo: self.uploadImageView.leftAnchor, constant: 4).isActive = true
self.inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
self.inputTextField.backgroundColor = UIColor.clear
//x,y,w,h
self.swiche.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 4).isActive = true
self.swiche.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
self.swiche.heightAnchor.constraint(equalToConstant: 30).isActive = true
self.swiche.widthAnchor.constraint(equalToConstant: 55).isActive = true
//x,y,w,h
self.uploadImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
self.uploadImageView.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
self.uploadImageView.widthAnchor.constraint(equalToConstant: 47).isActive = true
self.uploadImageView.heightAnchor.constraint(equalToConstant: 47).isActive = true
//x,y,w,h
self.separatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
self.separatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
self.separatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
self.separatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
return containerView
}()
//MARK: AccesoryView
override var inputAccessoryView: UIView? {
get {
return inputContainerView
}
}
Thanks for the help!!!

Just what I thought, all you need to do is accessing safeAreaLayoutGuide class before pointing out the constraint. In your case, you need to change constraints like these:
self.inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
Into constraint like these:
self.inputTextField.centerYAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.centerYAnchor).isActive = true
Let me know how it goes.

ok, paste this code before lazy var
override func didMoveToWindow() {
super.didMoveToWindow()
if #available(iOS 11.0, *) {
if let window = self.window {
self.bottomAnchor.constraintLessThanOrEqualToSystemSpacingBelow(window.safeAreaLayoutGuide.bottomAnchor, multiplier: 1.0).isActive = true
}
}
}
now your view is up safeAreaLayoutGuide...but at the bottom you can see the tableview because there is no background (your view is up safeAreaLayoutGuide), for correct the problem I built a white uiview, presented it in inputTextField and set the constraint:
let dummyView = UIView()
dummyView.backgroundColor = .white
dummyView.translatesAutoresizingMaskIntoConstraints = false
Now set the constraint:
inputTextField.addSubview(dummyView)
dummyView.topAnchor.constraint(equalTo: inputTextField.bottomAnchor).isActive = true
dummyView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
dummyView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
dummyView.heightAnchor.constraint(equalToConstant: 50).isActive = true
This is the hack, but I think that's Xcode bug... I hope this help you...

I hope that for your code you simply add this bottom constraint for inputTextField and in other elements is needed, and set containerView CGRect frame height to 100:
self.inputTextField.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor).isActive = true
and I suppose that you can delete:
self.inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true

Related

Can't Tap UIView in Nested ScrollView

I have a vertical UIScrollView, allScrollView, and a horizontal UIScrollView, hourlyScrollView, nested inside the vertical UIScrollView. In each of the scroll views I have 10 other UIViews that will show data. Each of the views are assigned a UITapGestureRecognizer. I'm able to tap the views that are only in the vertical scroll, but none of the views in the nested horizontal scroll do anything when tapped. If anyone can help me it would be greatly appreciated as I've tried a lot of suggestions on here with no luck.
my view hierarchy:
-allScrollView (vertical)
-allContentView
-hourlyScrollView (horizontal)
-hourlyContentView
-10 UIViews
-dailyContentView
-10 UIViews
viewDidLoad()
let dailyContentView = UIView()
let hourlyContentView = UIView()
let hourlyScrollView = UIScrollView()
let allContentView = UIView()
let allScrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
hourlyScrollView.translatesAutoresizingMaskIntoConstraints = false
hourlyContentView.translatesAutoresizingMaskIntoConstraints = false
allContentView.translatesAutoresizingMaskIntoConstraints = false
allScrollView.translatesAutoresizingMaskIntoConstraints = false
dailyContentView.translatesAutoresizingMaskIntoConstraints = false
layoutHourlyViews()
layoutDailyViews()
finishLayout()
}
create horizontal scroll content
func layoutHourlyViews() {
for subview in hourlyScrollView.subviews {
subview.removeFromSuperview()
}
for subView in hourlyContentView.subviews {
subView.removeFromSuperview()
}
var previousHour : UIView? = nil
for count in 1...10 {
let hourlyUIView = UIView()
hourlyUIView.backgroundColor = .blue
hourlyUIView.isUserInteractionEnabled = true
hourlyUIView.tag = count
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hourlyTap(_:)))
hourlyUIView.addGestureRecognizer(tapGesture)
let descriptionLabel = UILabel()
let borderView = UIView()
let borderViewTop = UIView()
let borderViewBottom = UIView()
borderViewTop.backgroundColor = .black
borderViewBottom.backgroundColor = .black
borderViewTop.translatesAutoresizingMaskIntoConstraints = false
borderViewBottom.translatesAutoresizingMaskIntoConstraints = false
borderView.translatesAutoresizingMaskIntoConstraints = false
hourlyUIView.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.text = "test"
borderView.backgroundColor = .black
hourlyUIView.addSubview(borderViewBottom)
hourlyUIView.addSubview(borderViewTop)
hourlyUIView.addSubview(descriptionLabel)
hourlyUIView.addSubview(borderView)
borderViewBottom.leadingAnchor.constraint(equalTo: hourlyUIView.leadingAnchor).isActive = true
borderViewBottom.trailingAnchor.constraint(equalTo: hourlyUIView.trailingAnchor).isActive = true
borderViewBottom.bottomAnchor.constraint(equalTo: hourlyUIView.bottomAnchor).isActive = true
borderViewBottom.heightAnchor.constraint(equalToConstant: 2).isActive = true
borderViewTop.leadingAnchor.constraint(equalTo: hourlyUIView.leadingAnchor).isActive = true
borderViewTop.trailingAnchor.constraint(equalTo: hourlyUIView.trailingAnchor).isActive = true
borderViewTop.topAnchor.constraint(equalTo: hourlyUIView.topAnchor).isActive = true
borderViewTop.heightAnchor.constraint(equalToConstant: 2).isActive = true
hourlyUIView.widthAnchor.constraint(equalToConstant: 160).isActive = true
hourlyUIView.heightAnchor.constraint(equalToConstant: 240).isActive = true
descriptionLabel.topAnchor.constraint(equalTo: hourlyUIView.topAnchor, constant: 16).isActive = true
descriptionLabel.centerXAnchor.constraint(equalTo: hourlyUIView.centerXAnchor, constant: 0).isActive = true
hourlyContentView.addSubview(hourlyUIView)
if previousHour == nil {
hourlyUIView.topAnchor.constraint(equalTo: hourlyContentView.topAnchor, constant: 0).isActive = true
hourlyUIView.leadingAnchor.constraint(equalTo: hourlyContentView.leadingAnchor, constant: 2).isActive = true
}
else {
hourlyUIView.topAnchor.constraint(equalTo: hourlyContentView.topAnchor, constant: 0).isActive = true
hourlyUIView.leadingAnchor.constraint(equalTo: previousHour!.trailingAnchor, constant: 0).isActive = true
borderView.bottomAnchor.constraint(equalTo: hourlyUIView.bottomAnchor).isActive = true
borderView.topAnchor.constraint(equalTo: hourlyUIView.topAnchor).isActive = true
borderView.widthAnchor.constraint(equalToConstant: 2).isActive = true
borderView.leadingAnchor.constraint(equalTo: hourlyUIView.leadingAnchor).isActive = true
}
previousHour = hourlyUIView
}
let borderViewTop = UIView()
let borderViewBottom = UIView()
borderViewTop.backgroundColor = .black
borderViewBottom.backgroundColor = .black
borderViewTop.translatesAutoresizingMaskIntoConstraints = false
borderViewBottom.translatesAutoresizingMaskIntoConstraints = false
hourlyScrollView.addSubview(hourlyContentView)
hourlyContentView.leadingAnchor.constraint(equalTo: hourlyScrollView.leadingAnchor, constant: 0).isActive = true
hourlyContentView.topAnchor.constraint(equalTo: hourlyScrollView.topAnchor, constant: 0).isActive = true
hourlyContentView.trailingAnchor.constraint(equalTo: hourlyScrollView.trailingAnchor, constant: 0).isActive = true
hourlyContentView.bottomAnchor.constraint(equalTo: hourlyScrollView.bottomAnchor, constant: 0).isActive = true
allContentView.addSubview(hourlyScrollView)
hourlyScrollView.isScrollEnabled = true
hourlyScrollView.topAnchor.constraint(equalTo: allContentView.topAnchor, constant: 20).isActive = true
hourlyScrollView.leadingAnchor.constraint(equalTo: allContentView.leadingAnchor, constant: 0).isActive = true
hourlyScrollView.trailingAnchor.constraint(equalTo: allContentView.trailingAnchor, constant: 0).isActive = true
}
create vertical scroll content
func layoutDailyViews() {
for subview in dailyContentView.subviews {
subview.removeFromSuperview()
}
var previousDay : UIView? = nil
for count in 1...10 {
let dailyUIView = UIView()
//dailyUIView.isUserInteractionEnabled = true
dailyUIView.tag = count
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dailyTap(_:)))
dailyUIView.addGestureRecognizer(tapGesture)
//hourlyUIView.frame.size = CGSize(width: 500, height: 50)
let descriptionLabel = UILabel()
dailyUIView.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.text = "daily test"
let borderView = UIView()
borderView.translatesAutoresizingMaskIntoConstraints = false
borderView.backgroundColor = .black
dailyUIView.addSubview(descriptionLabel)
dailyUIView.addSubview(borderView)
borderView.bottomAnchor.constraint(equalTo: dailyUIView.bottomAnchor).isActive = true
borderView.heightAnchor.constraint(equalToConstant: 2).isActive = true
borderView.leadingAnchor.constraint(equalTo: dailyUIView.leadingAnchor).isActive = true
borderView.trailingAnchor.constraint(equalTo: dailyUIView.trailingAnchor).isActive = true
dailyUIView.heightAnchor.constraint(equalToConstant: 100).isActive = true
descriptionLabel.leadingAnchor.constraint(equalTo: dailyUIView.leadingAnchor, constant: 16).isActive = true
descriptionLabel.centerYAnchor.constraint(equalTo: dailyUIView.centerYAnchor, constant: 0).isActive = true
dailyContentView.addSubview(dailyUIView)
if previousDay == nil {
dailyUIView.topAnchor.constraint(equalTo: dailyContentView.topAnchor, constant: 0).isActive = true
}
else {
dailyUIView.topAnchor.constraint(equalTo: previousDay!.bottomAnchor, constant: 0).isActive = true
}
dailyUIView.widthAnchor.constraint(equalToConstant: view.frame.width - 4).isActive = true
dailyUIView.centerXAnchor.constraint(equalTo: dailyContentView.centerXAnchor).isActive = true
previousDay = dailyUIView
}
allContentView.addSubview(dailyContentView)
}
func finishLayout() {
hourlyScrollView.bottomAnchor.constraint(equalTo: dailyContentView.bottomAnchor, constant: 0).isActive = true
dailyContentView.topAnchor.constraint(equalTo: allContentView.topAnchor, constant: 260).isActive = true
dailyContentView.centerXAnchor.constraint(equalTo: allContentView.centerXAnchor, constant: 0).isActive = true
dailyContentView.leadingAnchor.constraint(equalTo: allContentView.leadingAnchor).isActive = true
dailyContentView.trailingAnchor.constraint(equalTo: allContentView.trailingAnchor, constant: 0).isActive = true
dailyContentView.bottomAnchor.constraint(equalTo: allContentView.bottomAnchor).isActive = true
allScrollView.addSubview(allContentView)
allContentView.topAnchor.constraint(equalTo: allScrollView.topAnchor).isActive = true
allContentView.leadingAnchor.constraint(equalTo: allScrollView.leadingAnchor).isActive = true
allContentView.trailingAnchor.constraint(equalTo: allScrollView.trailingAnchor).isActive = true
allContentView.bottomAnchor.constraint(equalTo: allScrollView.bottomAnchor).isActive = true
allContentView.centerXAnchor.constraint(equalTo: allScrollView.centerXAnchor).isActive = true
allContentView.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true
allContentView.heightAnchor.constraint(equalToConstant: 1500).isActive = true
view.addSubview(allScrollView)
allScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
allScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
allScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
allScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
tapped functions
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hourlyScrollView.contentSize = CGSize(width:160 * 10 + 2, height:240)
allScrollView.contentSize = CGSize(width: view.frame.width, height:1500)
}
#objc func hourlyTap(_ sender: UITapGestureRecognizer) {
let tappedView = sender.view
print("hourly: \(tappedView!.tag)")
}
#objc func dailyTap(_ sender: UITapGestureRecognizer) {
let tappedView = sender.view
print("daily: \(tappedView!.tag)")
}
You haven't set all the required constraints on your hourlyContentView so the horizontal scrollView's size is (0,0) and as such it can't be scrolled or tapped. You can use Debug View Hierarchy in Xcode to see this.
The constraints you need to add are:
Between your last hourlyUIView's trailingAnchor and hourlyContentView's trailing anchor:
...
previousHour = hourlyUIView
}
previousHour?.trailingAnchor.constraint(equalTo: hourlyContentView.trailingAnchor).isActive = true
let borderViewTop = UIView()
let borderViewBottom = UIView()
...
Setting your hourlyContentView heightAnchor equal to the hourlyScrollView height anchor:
hourlyContentView.heightAnchor.constraint(equalTo: hourlyScrollView.heightAnchor).isActive = true

Vertical ScrollView not scrolling (No Storyboard)

I need help creating a Scroll View without Storyboards. Here is my code for setting up the Scroll View; I'm not setting a contentSize of the Scroll View because I'd like the scroll view content size to be dynamic, dependent on the amount of text in the TextView. What I did instead, is I tried adding a 'contentView' to the Scroll View and added all my UI elements into the contentView. Any help would be appreciated.
import Foundation
import UIKit
import UITextView_Placeholder
class ComposerVC: UIViewController {
private var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: UIScreen.main.bounds)
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
private var contentView: UIView = {
let content = UIView()
content.translatesAutoresizingMaskIntoConstraints = false
return content
}()
private var title: UITextView = {
let title = UITextView()
title.translatesAutoresizingMaskIntoConstraints = false
title.placeholder = "Untitled"
title.textColor = UIColor(hexString: "#50E3C2")
title.font = UIFont(name: "Rubik-BoldItalic", size: 32)
title.backgroundColor = .clear
title.isScrollEnabled = false
return title
}()
private var divider: UIView = {
let divider = UIView()
divider.translatesAutoresizingMaskIntoConstraints = false
divider.backgroundColor = UIColor(hexString: "#50E3C2")
return divider
}()
private var content: UITextView = {
let title = UITextView()
title.translatesAutoresizingMaskIntoConstraints = false
title.placeholder = "Begin writing here..."
title.textColor = .white
title.font = UIFont(name: "Avenir-Book", size: 15)
title.backgroundColor = .clear
title.isScrollEnabled = false
return title
}()
override func viewDidLoad() {
setupUI()
setupUIConstraints()
title.delegate = self
}
private func setupUI() {
view.backgroundColor = UIColor(hexString: "#131415")
view.addSubview(scrollView)
scrollView.addSubview(contentView)
contentView.addSubview(title)
contentView.addSubview(divider)
contentView.addSubview(content)
}
private func setupUIConstraints() {
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
title.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 95).isActive = true
title.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 35).isActive = true
title.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -35).isActive = true
divider.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 15).isActive = true
divider.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
divider.heightAnchor.constraint(equalToConstant: 1).isActive = true
divider.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.8).isActive = true
content.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: 15).isActive = true
content.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 35).isActive = true
content.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -35).isActive = true
}
}
extension ComposerVC: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
}
}
A couple tips:
Don't use existing names for variables... with your code as-is, private var title: UITextView causes problems (title is already a view controller property).
Use var names that imply the object... e.g. titleTextView and contentTextView instead of title and content
During development - particularly when you're working on layout - give your UI elements contrasting background colors so you can easily see their frames at runtime.
When using code-created views, set .clipsToBounds = true ... if you don't see any subviews you've added, you know the frame / constraints are missing something.
I don't have your UITextView_Placeholder import, but that shouldn't affect anything here...
So, first, change your viewDidLoad() to this:
override func viewDidLoad() {
setupUI()
setupUIConstraints()
titleTextView.delegate = self
// contrasting colors during development
scrollView.backgroundColor = .red
titleTextView.backgroundColor = .yellow
contentTextView.backgroundColor = .green
divider.backgroundColor = .blue
contentView.backgroundColor = .cyan
}
When you run it, you should see (scroll view background is red, and this is without the placeholder stuff):
It looks correct, except there's no cyan-colored contentView.
Now, clip the subviews of contentView:
private var contentView: UIView = {
let content = UIView()
content.translatesAutoresizingMaskIntoConstraints = false
// add this line
content.clipsToBounds = true
return content
}()
The result:
Where did everything go? Well, we didn't see the cyan contentView and now we don't see any of its subviews ... If we use Debug View Hierarchy we can find out contentView has a Height of Zero.
Fix that by constraining the bottom of the second text view in setupUIConstraints() (I've renamed it to contentTextView instead of just content):
contentTextView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -95).isActive = true
and we get:
Now the Height of the cyan contentView is controlled by correctly setup constraints of its subviews.
As a side note: with constraints setup properly, and scrolling disabled for the text views, you do not need your:
extension ComposerVC: UITextViewDelegate {
//func textViewDidChange(_ textView: UITextView) {
//...
//}
}
The text view will automatically size itself to its text:
Here's the complete edited code:
class ComposerVC: UIViewController {
private var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: UIScreen.main.bounds)
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
private var contentView: UIView = {
let content = UIView()
content.translatesAutoresizingMaskIntoConstraints = false
// add this line so we know if the constraints are set correctly
content.clipsToBounds = true
return content
}()
private var titleTextView: UITextView = {
let title = UITextView()
title.translatesAutoresizingMaskIntoConstraints = false
// title.placeholder = "Untitled"
title.textColor = UIColor(hexString: "#50E3C2")
title.font = UIFont(name: "Rubik-BoldItalic", size: 32)
title.backgroundColor = .clear
title.isScrollEnabled = false
return title
}()
private var divider: UIView = {
let divider = UIView()
divider.translatesAutoresizingMaskIntoConstraints = false
divider.backgroundColor = UIColor(hexString: "#50E3C2")
return divider
}()
private var contentTextView: UITextView = {
let title = UITextView()
title.translatesAutoresizingMaskIntoConstraints = false
// title.placeholder = "Begin writing here..."
title.textColor = .white
title.font = UIFont(name: "Avenir-Book", size: 15)
title.backgroundColor = .clear
title.isScrollEnabled = false
return title
}()
override func viewDidLoad() {
setupUI()
setupUIConstraints()
titleTextView.delegate = self
// contrasting colors during development
scrollView.backgroundColor = .red
titleTextView.backgroundColor = .yellow
contentTextView.backgroundColor = .green
divider.backgroundColor = .blue
contentView.backgroundColor = .cyan
}
private func setupUI() {
view.backgroundColor = UIColor(hexString: "#131415")
view.addSubview(scrollView)
scrollView.addSubview(contentView)
contentView.addSubview(titleTextView)
contentView.addSubview(divider)
contentView.addSubview(contentTextView)
}
private func setupUIConstraints() {
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
titleTextView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 95).isActive = true
titleTextView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 35).isActive = true
titleTextView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -35).isActive = true
divider.topAnchor.constraint(equalTo: titleTextView.bottomAnchor, constant: 15).isActive = true
divider.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
divider.heightAnchor.constraint(equalToConstant: 1).isActive = true
divider.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.8).isActive = true
contentTextView.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: 15).isActive = true
contentTextView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 35).isActive = true
contentTextView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -35).isActive = true
contentTextView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -95).isActive = true
}
}
extension ComposerVC: UITextViewDelegate {
// func textViewDidChange(_ textView: UITextView) {
// let fixedWidth = textView.frame.size.width
// let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
// textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
// }
}
Assuming you are using iOS 11+, Your contentView should have its anchors constrained to the contentLayoutGuide of the scrollView. like this:
contentView
.leadingAnchor
.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor).isActive = true
contentView
.topAnchor
.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor).isActive = true
contentView
.trailingAnchor
.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor).isActive = true
contentView
.bottomAnchor
.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor).isActive = true
Also, its width should be constrained to the scrollView's frameLayoutGuide and not the view's width, like this:
contentView
.widthAnchor
.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor).isActive = true
That should make the scrollView detect the content size to fit.

How do I add a UIView to a UIScrollView In Swift programmatically?

I am trying to add a view to a UIScrollView just using code, but the view doesn't appear in the UIScrollView and I'm not sure why. When I added a button or label, they show up.
import UIKit
class profileViewController: UIViewController, UIScrollViewDelegate {
var label : UILabel = {
let label = UILabel()
label.text = "Profile"
label.textColor = UIColor.init(white: 0.80, alpha: 1)
label.font = UIFont.systemFont(ofSize: 40)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var scrollview : UIScrollView = {
let scrollview = UIScrollView()
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.backgroundColor = .clear
return scrollview
}()
var greyview : UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.init(white: 0.70, alpha: 1)
view.backgroundColor = UIColor.gray
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(label)
label.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
label.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
scrollview.delegate = self
view.addSubview(scrollview)
scrollview.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollview.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollview.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollview.contentSize = CGSize.init(width: view.frame.size.width, height: view.frame.size.height + 500)
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.trailingAnchor.constraint(equalTo: scrollview.trailingAnchor).isActive = true
greyview.leadingAnchor.constraint(equalTo: scrollview.leadingAnchor).isActive = true
greyview.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
}
this is one way:
self.scrollView = UIScrollView.init()
if let scrollView = self.scrollView {
scrollView.showsVerticalScrollIndicator = true
self.view.add(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraint(UtilConstraint.addTopConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addBottomConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addLeftLeftConstraint(from: scrollView, to: self, value: 0))
self.addConstraint(UtilConstraint.addRightRightConstraint(from: scrollView, to: self, value: 0))
NSLayoutConstraint.activate(self.constraints)
greyview.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
greyview.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
greyview.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
greyview.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
}
Remember, your greyview should have hight defined either statically or via. components inside.
though , what you were missing was defining a width. I have done it using widthAnchor. (assuming you need a vertical scroll)
This is probably because your greyview doesnt have its bottomAnchor. It needs the top and bottom anchors in order to work properly inside the scrollView:
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.centerXAnchor.constraint(equalTo: scrollview.centerXAnchor).isActive = true
greyview.heightAnchor.constraint(equalToConstant: 100).isActive = true
greyview.widthAnchor.constraint(equalToConstant: 100).isActive = true
Add a widthAnchor, here I centered it in the scroll view but it is up to you to place it how you want it. Also if you add more items just make sure the bottom-most item has a bottomAnchor attached to the scrollView bottomAnchor or it will not scroll.
Update:
I don't know how you want your greyview to look, but if you make the height taller than the contentSize of the scrollView it will scroll, and make sure you have the bottomAnchor:
scrollview.contentSize = CGSize.init(width: view.frame.size.width, height: view.frame.size.height)
scrollview.addSubview(greyview)
greyview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
greyview.bottomAnchor.constraint(equalTo: scrollview.bottomAnchor).isActive = true
greyview.heightAnchor.constraint(equalTo: scrollview.heightAnchor, constant: 500).isActive = true
greyview.widthAnchor.constraint(equalTo: scrollview.widthAnchor).isActive = true
This makes the greyview width equal to scrollview width, and height equal to scrollview height + 500 so that it scrolls.

How can I show a hidden UIButton?

Views were placed using code.
If I press deleteButton (button), I want the hidden button(imgButton) to appear.
However, imgView's width is not refresh.
MainViewController.swift
import UIKit
class MainViewController: UIViewController {
var trashIsSelected: Bool!
let imgButton: UIButton = {
let imgView = UIButton()
imgView.setImage(UIImage(named: "schedule_delete_icon"), for: UIControlState.normal)
// imgView.imageView?.image = UIImage(named: "schedule_delete_icon")
imgView.translatesAutoresizingMaskIntoConstraints = false
return imgView
}()
let deleteButton: UIButton = {
let imgBtn = UIButton()
imgBtn.setImage(UIImage(named: "icon_delete"), for: UIControlState.normal)
// imgBtn.imageView?.image = UIImage(named: "icon_delete")
imgBtn.translatesAutoresizingMaskIntoConstraints = false
return imgBtn
}()
let label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "하ㅣㅇ하이히아히아하하하하ㅏㅎ하ㅏㅎ하ㅏ하하하하ㅏㅏ하하하하하ㅏ"
return label
}()
var imgViewWidth: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
}
func setupLayout(){
let testView = UIScrollView()
self.view.addSubview(testView)
testView.backgroundColor = .lightGray
testView.translatesAutoresizingMaskIntoConstraints = false
testView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
testView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
testView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
testView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.3).isActive = true
testView.addSubview(imgButton)
testView.addSubview(label)
imgButton.leadingAnchor.constraint(equalTo: testView.leadingAnchor, constant: 10).isActive = true
imgButton.centerYAnchor.constraint(equalTo: testView.centerYAnchor).isActive = true
imgButton.heightAnchor.constraint(equalTo: testView.heightAnchor, multiplier: 0.2).isActive = true
imgButton.widthAnchor.constraint(equalTo: imgButton.heightAnchor, multiplier: 0).isActive = true
imgButton.isHidden = true
trashIsSelected = false
label.centerYAnchor.constraint(equalTo: testView.centerYAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: imgButton.trailingAnchor, constant: 10).isActive = true
label.heightAnchor.constraint(equalTo: testView.heightAnchor, multiplier: 0.2).isActive = true
label.widthAnchor.constraint(equalTo: testView.widthAnchor, multiplier: 0.5).isActive = true
self.view.addSubview(deleteButton)
deleteButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
deleteButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
deleteButton.addTarget(self, action: #selector(self.addBtnAction(_:)), for: UIControlEvents.touchUpInside)
}
#objc func addBtnAction(_ sender: UIButton){
print("hi")
if trashIsSelected == false{
trashIsSelected = true
imgButton.isHidden = false
imgButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
imgButton.updateConstraints()
}else{
trashIsSelected = false
imgButton.widthAnchor.constraint(equalToConstant: 0).isActive = true
imgButton.isHidden = true
imgButton.updateConstraints()
}
}
}
This is error message:
2018-05-23 14:00:47.697959+0900 Test[67488:4887863] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"",
""
)
Will attempt to recover by breaking constraint
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.
You are adding new constraints to the button that conflict with the old ones (how can a button be 0 points wide, and simultaneously 50 points wide?). To make it work, you need to turn off the old constraint before you activate a new one. I recommend creating a property that would keep the current imgButton constraint at all times, and then when you want to change it, just use that (either turn it off and create a new one, or just set a constant, which in your case is better and easier):
import UIKit
class MainViewController: UIViewController {
// property referencing current imgButton width constraint
fileprivate var imgButtonWidthConstraint: NSLayoutConstraint!
var trashIsSelected: Bool!
let imgButton: UIButton = {
let imgView = UIButton()
imgView.setImage(UIImage(named: "schedule_delete_icon"), for: UIControlState.normal)
// imgView.imageView?.image = UIImage(named: "schedule_delete_icon")
imgView.translatesAutoresizingMaskIntoConstraints = false
return imgView
}()
let deleteButton: UIButton = {
let imgBtn = UIButton()
imgBtn.setImage(UIImage(named: "icon_delete"), for: UIControlState.normal)
// imgBtn.imageView?.image = UIImage(named: "icon_delete")
imgBtn.translatesAutoresizingMaskIntoConstraints = false
return imgBtn
}()
let label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "하ㅣㅇ하이히아히아하하하하ㅏㅎ하ㅏㅎ하ㅏ하하하하ㅏㅏ하하하하하ㅏ"
return label
}()
var imgViewWidth: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
}
func setupLayout(){
let testView = UIScrollView()
self.view.addSubview(testView)
testView.backgroundColor = .lightGray
testView.translatesAutoresizingMaskIntoConstraints = false
testView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
testView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
testView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
testView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.3).isActive = true
testView.addSubview(imgButton)
testView.addSubview(label)
imgButton.leadingAnchor.constraint(equalTo: testView.leadingAnchor, constant: 10).isActive = true
imgButton.centerYAnchor.constraint(equalTo: testView.centerYAnchor).isActive = true
imgButton.heightAnchor.constraint(equalTo: testView.heightAnchor, multiplier: 0.2).isActive = true
// keep the reference to constraint that defines width
// (we will use the constraint setting the width to constant, since then you can
// simply switch the constant between 0 and 50):
imgButtonWidthConstraint = imgButton.widthAnchor.constraint(equalToConstant: 0)
imgButtonWidthConstraint.isActive = true
imgButton.isHidden = true
trashIsSelected = false
label.centerYAnchor.constraint(equalTo: testView.centerYAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: imgButton.trailingAnchor, constant: 10).isActive = true
label.heightAnchor.constraint(equalTo: testView.heightAnchor, multiplier: 0.2).isActive = true
label.widthAnchor.constraint(equalTo: testView.widthAnchor, multiplier: 0.5).isActive = true
self.view.addSubview(deleteButton)
deleteButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
deleteButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
deleteButton.addTarget(self, action: #selector(self.addBtnAction(_:)), for: UIControlEvents.touchUpInside)
}
#objc func addBtnAction(_ sender: UIButton){
print("hi")
if trashIsSelected == false{
trashIsSelected = true
imgButton.isHidden = false
// just change the constant to what you want
imgButtonWidthConstraint.constant = 50
imgButton.updateConstraints()
} else {
trashIsSelected = false
imgButtonWidthConstraint.constant = 0
imgButton.isHidden = true
imgButton.updateConstraints()
}
}
}
EDIT:
Just for completeness of the answer, if you were for some reason using constraints where changing a constant would not be enough, you would have to activate and deactivate the constraints. E.g., if you were using multiplier to determine imgButton's width, you would have to use this approach (multiplier is an immutable property of the NSLayoutConstraint). So therefore creating a constraint:
// simply switch the constant between 0 and 50):
imgButtonWidthConstraint = imgButton.widthAnchor.constraint(equalTo: someOtherView.widthAnchor, multiplier: 0)
imgButtonWidthConstraint.isActive = true
And then in addBtnAction you would have to do to this:
#objc func addBtnAction(_ sender: UIButton){
print("hi")
if trashIsSelected == false{
trashIsSelected = true
imgButton.isHidden = false
// first deactivate current constraint
imgButtonWidthConstraint.isActive = false
// then create a new one and store it to imgButtonWidthConstraint property (the old one is deactivated, so you don't need a reference to it anymore)
imgButtonWidthConstraint = imgButton.widthAnchor.constraint(equalTo: someOtherView.widthAnchor, multiplier: 0.75)
// and activate the new one
imgButtonWidthConstraint.isActive = true
imgButton.updateConstraints()
} else {
trashIsSelected = false
// same process again
imgButtonWidthConstraint.isActive = false
imgButtonWidthConstraint = imgButton.widthAnchor.constraint(equalTo: someOtherView.widthAnchor, multiplier: 0)
imgButtonWidthConstraint.isActive = true
imgButton.isHidden = true
imgButton.updateConstraints()
}
}

Programmatically layed out UIScrollView, and added auto layout to it's subviews, but it does not scroll

I am trying to figure out how UIScrollView works and I added some subviews to it with different backgroundColor properties. I layed out the subviews with ios9 autolayout but even if the views are outside of the screen, the UIScrollView still does not scroll.
import UIKit
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.backgroundColor = .gray
return sv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
let view1 = UIView()
view1.backgroundColor = .red
let view2 = UIView()
view2.backgroundColor = .blue
let view3 = UIView()
view3.backgroundColor = .green
let view4 = UIView()
view4.backgroundColor = .purple
let views = [view1, view2, view3, view4]
for view in views {
scrollView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
}
view1.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
view1.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
view1.heightAnchor.constraint(equalToConstant: 140).isActive = true
view1.widthAnchor.constraint(equalToConstant: 140).isActive = true
view2.topAnchor.constraint(equalTo: view1.bottomAnchor, constant: 100).isActive = true
view2.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view2.heightAnchor.constraint(equalToConstant: 140).isActive = true
view2.widthAnchor.constraint(equalToConstant: 140).isActive = true
view3.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 50).isActive = true
view3.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view3.heightAnchor.constraint(equalToConstant: 140).isActive = true
view3.widthAnchor.constraint(equalToConstant: 140).isActive = true
view4.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 20).isActive = true
view4.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
view4.heightAnchor.constraint(equalToConstant: 140).isActive = true
view4.widthAnchor.constraint(equalToConstant: 140).isActive = true
}
}
When using Autolayout in UIScrollViews you have to pin subviews both to the top and bottom of the scrollview which allows the scrollview to calculate its contentSize.
Adding this line fixes it:
view4.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true

Resources