try to set up a Dynamic UIScrollView programmatically but met problem - ios

recently I tried to set up a dynamic UIScrollView according to this website : https://medium.com/#javedmultani16/uiscrollview-dynamic-content-size-through-storyboard-in-ios-fb873e9278e
I tried to make one step by step, but seems like I have misunderstood something but I can't figure it out. Here is my code, I tried to add 30 UITextField and set the UIScrollView equal height with those contents.
Problem I met, the scrollview not work correctly, it can only scroll a little bit, like I can only scroll to about 8 or 9 line , the others below I can't scroll down.
override func viewDidLoad() {
super.viewDidLoad()
//Step 1
let scrollview = UIScrollView()
view.addSubview(scrollview)
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollview.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollview.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollview.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollview.alwaysBounceVertical = true
//Step 2
let oneview = UIView()
scrollview.addSubview(oneview)
oneview.translatesAutoresizingMaskIntoConstraints = false
oneview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
oneview.bottomAnchor.constraint(equalTo: scrollview.bottomAnchor).isActive = true
oneview.leadingAnchor.constraint(equalTo: scrollview.leadingAnchor).isActive = true
oneview.trailingAnchor.constraint(equalTo: scrollview.trailingAnchor).isActive = true
oneview.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
let heightConstraint = oneview.heightAnchor.constraint(equalTo: view.heightAnchor)
heightConstraint.isActive = true
heightConstraint.priority = .defaultLow
//Step 3
for i in 1...30{
let field = UITextField()
field.placeholder = "This is line "+String(i+1)
field.backgroundColor = .gray
field.isUserInteractionEnabled = false
oneview.addSubview(field)
field.translatesAutoresizingMaskIntoConstraints = false
field.widthAnchor.constraint(equalTo: oneview.widthAnchor, multiplier: 0.8).isActive = true
field.heightAnchor.constraint(equalToConstant: 50).isActive = true
field.centerXAnchor.constraint(equalTo: oneview.centerXAnchor).isActive = true
field.topAnchor.constraint(equalTo: oneview.topAnchor, constant: CGFloat(100*i)).isActive = true
}
}

The whole point of using this dummy subview (oneview in your code) is so that its contents can tell the dummy subview what height it should be, and the scroll view's content size will fit that height.
However, your textfield's constraints do not suggest a height for oneview!. All your textfields' constraints say is the text fields
should be some distance below the top of oneview.
should be a certain height
should have the same centre X as oneview
should have the same width as oneview
To satisfy the above, oneview's height doesn't need to change at all. The layout engine can just place your text fields outside of the bounds of oneview, and still satisfy the above constraints. (Think about it!)
But, if you add one more constraint to the last text field, that it
should be a certain distance above the bottom of oneview
then oneview has to resize in order to satisfy that. You are indirectly implying a height for oneview, because you are saying
for the last text field, I want this much space to be above it, and this much space to be below it.
We could just make that "certain distance" zero as well. Here's how you would do it in code:
// in the loop...
if i == 30 {
field.bottomAnchor.constraint(equalTo: oneview.bottomAnchor).isActive = true
}
An even better way to tell oneview its height would be to use a UIStackView. Replace steps 2 and 3 with:
let oneview = UIStackView()
oneview.alignment = .fill
oneview.distribution = .equalSpacing
oneview.spacing = 50
oneview.axis = .vertical
scrollview.addSubview(oneview)
oneview.translatesAutoresizingMaskIntoConstraints = false
oneview.topAnchor.constraint(equalTo: scrollview.topAnchor).isActive = true
oneview.bottomAnchor.constraint(equalTo: scrollview.bottomAnchor).isActive = true
oneview.leadingAnchor.constraint(equalTo: scrollview.leadingAnchor).isActive = true
oneview.trailingAnchor.constraint(equalTo: scrollview.trailingAnchor).isActive = true
oneview.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
let heightConstraint = oneview.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 25)
heightConstraint.isActive = true
heightConstraint.priority = .defaultLow
for i in 1...30{
let field = UITextField()
field.placeholder = "This is line "+String(i+1)
field.backgroundColor = .gray
field.isUserInteractionEnabled = false
oneview.addArrangedSubview(field)
field.translatesAutoresizingMaskIntoConstraints = false
field.heightAnchor.constraint(equalToConstant: 50).isActive = true
}

The problem is the first top view should be anchored to the top of the content view and the last bottom view should anchored to the bottom of the contentView
Extensions
extension UIScrollView {
func assignKeyboardObservers() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillDissmiss),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
#objc fileprivate func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
insetScrollView(insetBottom: keyboardHeight)
}
}
#objc fileprivate func keyboardWillDissmiss(_ notification: Notification) {
insetScrollView(insetBottom: 0)
}
fileprivate func insetScrollView(insetBottom: CGFloat) {
var inset:UIEdgeInsets = contentInset
inset.bottom = insetBottom
UIView.animate(withDuration: 0.2, animations: {
self.contentInset = inset
})
}
}
extension UIViewController {
func addScrollViewToView(paddingContentView:UIEdgeInsets = .zero, anchorScroll:( _ scrollView: inout UIScrollView)->())->UIView {
let tapToDismiss = UITapGestureRecognizer(target: self, action: #selector(dimissKeyboard(_:)))
tapToDismiss.cancelsTouchesInView = false
view.addGestureRecognizer(tapToDismiss)
var scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.bounces = true
scrollView.isScrollEnabled = true
scrollView.assignKeyboardObservers()
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
anchorScroll(&scrollView)
scrollView.addSubview(contentView)
NSLayoutConstraint.activate([
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: paddingContentView.top),
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: paddingContentView.left),
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -paddingContentView.right),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -paddingContentView.bottom),
contentView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
return contentView
}
#objc fileprivate func dimissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
}
How to use it
import UIKit
class TESTViewController: UIViewController {
private var contentView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
contentView = addScrollViewToView(anchorScroll: { (scrollView) in
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
])
})
let stackView:UIStackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 3
stackView.alignment = .fill
stackView.distribution = .fillEqually
for i in 1...30{
let field = UITextField()
field.translatesAutoresizingMaskIntoConstraints = false
field.placeholder = "This is line "+String(i+1)
field.backgroundColor = .gray
field.isUserInteractionEnabled = false
field.heightAnchor.constraint(equalToConstant: 50).isActive = true
stackView.addSubview(field)
}
contentView.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: contentView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
])
}
}

Related

UIHostingController not working with UIScrollView

EDIT
I am trying to place a UIHostingController within a UIScrollView but when I try to present the SumViewController the view has no height like in the picture.
If I set the height in the SwiftUI view then it works but I do not want to set the height of the view.
class SummaryViewController: UIViewController {
var id: String = ""
var sport: String = ""
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = UIStackView.Distribution.equalSpacing
stackView.spacing = 30
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
lazy var contentView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemGroupedBackground
let hosting = UIHostingController(rootView: SummaryView(id: id, sport: sport))
view.addSubview(scrollView)
scrollView.addSubview(contentView)
contentView.addSubview(stackView)
stackView.addArrangedSubview(hosting.view)
scrollView.insetsLayoutMarginsFromSafeArea = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
hosting.view.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.size.height).isActive = true
}
}

Animating Hiding Subviews in UIStackView goes out of screen

I'm trying to animate the hiding of the arranged subviews of a UIStackView:
UIView.animate(withDuration: 3, delay: 0) {
self.stackView.subviews.forEach({ $0.isHidden = true })
self.stackView.updateConstraintsIfNeeded()
self.stackView.layoutIfNeeded()
self.view.layoutIfNeeded()
} completion: { (_) in
self.children.forEach({ $0.removeFromParent() })
completion()
}
The problem is the views while animating expand in their width across the screen (out of screen bounds).
This is how the views are setup:
scrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
stackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
contentView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
contentView.addSubview(stackView)
scrollView.addSubview(contentView)
view.addSubview(scrollView)
scrollView.showsVerticalScrollIndicator = false
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20).isActive = true
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20).isActive = true
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -50).isActive = true
Question: How can I animate it in such a way, that it does not change width during the animation?
I don't know if this is a weird issue of the UIStackView or it serves some purpose, but: putting an "invisible" UIView into your UIStackView will fix the issue. Tag it, so when hiding the other elements it remains visible:
let imposterView = UIView()
imposterView.tag = 999
stackView.addArrangedSubview(imposterView)
Of course handle your hiding logic accordingly:
stackView.subviews.forEach({
if $0.tag != 999 {
$0.isHidden = 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.

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