Programatically created UIPageControl not showing - swift

In my view hierarchy, I have a UIPageViewController (inside a container view). Underneath that is the UIPageControl and at the bottom is a stack view consisting of a text view and a button. I see the UIPageViewController and the stack view but not the UIPageControl. Any idea what I am doing wrong:
// Page view controller
introPageViewC = IntroPageViewC()
addChild(introPageViewC)
introPageViewC.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(introPageViewC.view)
NSLayoutConstraint.activate([
introPageViewC.view.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0),
introPageViewC.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0),
introPageViewC.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0.0),
introPageViewC.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0.0),
])
introPageViewC.didMove(toParent: self)
// Page view control
introPageControl.currentPageIndicatorTintColor = UIColor.orange
introPageControl.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.8)
view.addSubview(introPageControl)
introPageControl.translatesAutoresizingMaskIntoConstraints = false
introPageControl.topAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 10).isActive = true
introPageControl.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// Stack view
view.addSubview(stackView)
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.spacing = 30
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: introPageControl.bottomAnchor, constant: 10).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40).isActive = true
Expected output:
Edit:
Attempt at adding to the stack view:
var allViews = [UIView]()
// Adding to stackview
introPageControl.currentPageIndicatorTintColor = UIColor.orange
introPageControl.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.8)
allViews.append(introPageControl)
nameTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
nameTextField.placeholder = "Mealplan name"
Utilities.styleTextField(nameTextField)
nameTextField.setPadding()
allViews.append(nameTextField)
let nextButton = UIButton(type: .system)
nextButton.frame = CGRect(x: 20, y: 20, width: 100, height: 40)
nextButton.setTitle("Next", for: .normal)
nextButton.titleLabel?.textColor = .white
nextButton.titleLabel?.font = UIFont(name: "NexaBold", size: 16)
Utilities.styleDefaultButton(nextButton)
nextButton.addTarget(self, action: #selector(tapSubmit(_:)), for: .touchUpInside)
allViews.append(nextButton)
errorLabel.frame = CGRect(x: 20, y: 20, width: 100, height: 40)
errorLabel.font = UIFont(name: "NexaBold", size: 16)
errorLabel.textColor = .systemRed
errorLabel.textAlignment = .center
errorLabel.alpha = 0
allViews.append(errorLabel)
for eachView in allViews {
stackView.addArrangedSubview(eachView)
}

introPageControl.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
I believe you meant centerXAnchor?

I think you've got the topAnchor all wrong. Right now, it seems to be constrained to the bottom of the containerView plus 10, which is just off the screen. I think you meant to say -10.
introPageControl.topAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -10).isActive = true

Related

(Swift) StackView in ScrollView doesn't work

I want to make a stackView in scrollView.
In stackView, I wanted to added some another stackViews, but it didn't work.
So, to simplify, I added some UIViews with addArrangedSubview() but it doesn't show anything.
How can I solve this? I spent a lot of my time...
scrollView = UIScrollView()
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor),
scrollView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor),
scrollView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
scrollView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])
var line1 = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 1000))
line1.backgroundColor = .blue
var line2 = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 1000))
line2.backgroundColor = .green
profile()
stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
])
stackView.addArrangedSubview(line1)
stackView.addArrangedSubview(line2)
stackView.updateConstraints()
stackView.setNeedsLayout()
I guess at the moment this code is running, the ViewControllers - view is still not set, so the width of your line1/2 will result in 0.
You should use auto layout to layout your views too.
var line1 = UIView()
line1.translatesAutoresizingMaskIntoConstraints = false
line1.backgroundColor = .blue
var line2 = UIView()
line1.translatesAutoresizingMaskIntoConstraints = false
line2.backgroundColor = .green
stackView = UIStackView(arrangedSubviews: [line1, line2])
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
line1.widthAnchor.constraint(equalTo: view.widthAnchor),
line1.heightAnchor.constraint(equalToConstant: 1000),
line2.widthAnchor.constraint(equalTo: view.widthAnchor),
line2.heightAnchor.constraint(equalToConstant: 1000),
])

The shadow added to the view created is not appearing

I am adding programatically a UIView, and setting its contsraints using NSLayoutConstraint as below, yet teh shadow is not being added.
For the shadow i am using SwifterSwift .addShadow()
UiView:
lazy var alertViewNew: UIView = {
let view = UIView()
view.layer.zPosition = 1
view.cornerRadius = 20
view.addShadow(ofColor: .lightGray, radius: 3, offset: .zero, opacity: 0.3)
view.translatesAutoresizingMaskIntoConstraints = false
return alertView
}()
Adding the Constaraints
func setUpAlertView() {
[alertViewNew].forEach {
(view.addSubview($0))
}
NSLayoutConstraint.activate([
alertViewNew.centerYAnchor.constraint(equalTo: view.centerYAnchor),
alertViewNew.centerXAnchor.constraint(equalTo: view.centerXAnchor),
alertViewNew.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
alertViewNew.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
titleLabel.leadingAnchor.constraint(equalTo: alertViewNew.leadingAnchor, constant: 20),
titleLabel.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
titleLabel.topAnchor.constraint(equalTo: alertViewNew.topAnchor, constant: 20),
descriptionLabel.leadingAnchor.constraint(equalTo: alertViewNew.leadingAnchor, constant: 20),
descriptionLabel.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20),
updateButton.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 5),
updateButton.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
updateButton.widthAnchor.constraint(equalToConstant: 65),
updateButton.bottomAnchor.constraint(equalTo: alertViewNew.bottomAnchor, constant: -20),
])
}
AddShadow by Swifter Swift
func addShadow(ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0), radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
layer.masksToBounds = false
}
Things i tried to fix the issue
Setting mask to bound to true
setting is opaque to true
and some other trials found on stackoverflow
None of this worked
It's a bit difficult to help, because the code you've shown is incomplete (and has errors, as written).
For example, I assume your func addShadow is in a UIView extension like this:
extension UIView {
func addShadow(ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0), radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
// no need for this
//layer.masksToBounds = false
}
}
Next, your lazy var alertViewNew:
lazy var alertViewNew: UIView = {
let view = UIView()
// no logical reason for this
//view.layer.zPosition = 1
// .cornerRadius is not a property of `UIView`
//view.cornerRadius = 20
// assuming this is in a UIView extension
view.addShadow(ofColor: .lightGray, radius: 3, offset: .zero, opacity: 0.3)
view.translatesAutoresizingMaskIntoConstraints = false
// no such thing as alertView
//return alertView
return view
}()
However... if we assume you have code that actually works (labels are defined and created somewhere, subviews are added correctly, etc), the most likely reason you're not seeing the shadow is because your alertViewNew probably has a clear background. If it is clear, there is nothing there to "cast a shadow."
Try setting alertViewNew.backgroundColor = .white and see if that fixes the problem.
Or, try this working example:
class CustomAlertTestVC: UIViewController {
lazy var alertViewNew: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(alertViewNew)
setUpAlertView()
}
func setUpAlertView() {
let titleLabel = UILabel()
let descriptionLabel = UILabel()
let updateButton = UIButton()
titleLabel.font = .boldSystemFont(ofSize: 16.0)
titleLabel.text = "New Version Available"
descriptionLabel.font = .systemFont(ofSize: 16.0)
descriptionLabel.numberOfLines = 0
descriptionLabel.text = "Please, Update application to the new version to continue."
updateButton.setTitle("UPDATE", for: [])
updateButton.setTitleColor(.systemBlue, for: [])
[titleLabel, descriptionLabel, updateButton].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
alertViewNew.addSubview($0)
}
NSLayoutConstraint.activate([
alertViewNew.centerYAnchor.constraint(equalTo: view.centerYAnchor),
// no need for centerX since we're adding leading and trailing constraints
//alertViewNew.centerXAnchor.constraint(equalTo: view.centerXAnchor),
alertViewNew.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
alertViewNew.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
titleLabel.leadingAnchor.constraint(equalTo: alertViewNew.leadingAnchor, constant: 20),
titleLabel.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
titleLabel.topAnchor.constraint(equalTo: alertViewNew.topAnchor, constant: 20),
descriptionLabel.leadingAnchor.constraint(equalTo: alertViewNew.leadingAnchor, constant: 20),
descriptionLabel.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20),
updateButton.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 5),
updateButton.trailingAnchor.constraint(equalTo: alertViewNew.trailingAnchor, constant: -20),
// really no need for width constraint
//updateButton.widthAnchor.constraint(equalToConstant: 65),
updateButton.bottomAnchor.constraint(equalTo: alertViewNew.bottomAnchor, constant: -20),
])
alertViewNew.layer.shadowColor = UIColor.lightGray.cgColor
alertViewNew.layer.shadowOffset = .zero
alertViewNew.layer.shadowRadius = 3.0
alertViewNew.layer.shadowOpacity = 0.3
alertViewNew.layer.cornerRadius = 20.0
// to get the view's layer to "cast a shadow"
// either set the view's backgroundColor
alertViewNew.backgroundColor = .white
// or, set the layer's backgroundColor
//alertViewNew.layer.backgroundColor = UIColor.white.cgColor
}
}
Output:

add 2 image views to a uiscrollview func every time it is called

My swift code below goal is to add 2 image views every time. Ass you can in the gif below only one image view is being added. I just need to add 2 image views. The image views are lastImage and lastImage2. you can see only lastImage is being shown. It seems I can only add 1 imageview when func didclickadd is called.
import UIKit
class ViewController: UIViewController {
fileprivate var lastImage:UIImageView?
fileprivate var lastImage2:UIImageView?
fileprivate var mainViewBootom:NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupVIew()
}
override func viewDidAppear(_ animated: Bool) {
scrollView.contentSize = CGSize(width: view.frame.width, height: mainView.frame.height)
view.layoutIfNeeded()
}
//MARK: Components
let scrollView:UIScrollView = {
let sv = UIScrollView(frame: .zero)
return sv
}()
let mainView:UIView = {
let uv = UIView()
uv.backgroundColor = .white
return uv
}()
let btnAdd:UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Add", for: .normal)
return btn
}()
let textField:UITextField = {
let jake = UITextField()
return jake
}()
//MARK: Setup UI
func setupVIew() {
view.addSubview(scrollView)
view.addSubview(btnAdd)
view.addSubview(textField)
scrollView.translatesAutoresizingMaskIntoConstraints = false
btnAdd.translatesAutoresizingMaskIntoConstraints = false
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
btnAdd.centerXAnchor.constraint(equalTo: view.centerXAnchor),
btnAdd.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -12),
btnAdd.widthAnchor.constraint(equalToConstant: 100),
btnAdd.heightAnchor.constraint(equalToConstant: 45),
//
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 25),
textField.widthAnchor.constraint(equalToConstant: 100),
textField.heightAnchor.constraint(equalToConstant: 45),
//
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: btnAdd.topAnchor , constant: -12),
])
btnAdd.addTarget(self, action: #selector(didClickedAdd), for: .touchUpInside)
scrollView.addSubview(mainView)
mainView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
mainView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mainView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mainView.topAnchor.constraint(equalTo: scrollView.topAnchor),
])
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 100))
imgView.backgroundColor = .red
mainView.addSubview(imgView)
let samsam = UIImageView(frame: CGRect(x: 0, y: 200, width: 40, height: 100))
samsam.backgroundColor = .blue
mainView.addSubview(samsam)
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imgView.widthAnchor.constraint(equalToConstant: 150).isActive = true
imgView.heightAnchor.constraint(equalToConstant: 100).isActive = true
samsam.translatesAutoresizingMaskIntoConstraints = false
samsam.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
samsam.topAnchor.constraint(equalTo: imgView.bottomAnchor).isActive = true
samsam.widthAnchor.constraint(equalToConstant: 75).isActive = true
samsam.heightAnchor.constraint(equalToConstant: 100).isActive = true
if lastImage != nil {
imgView.topAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 20).isActive = true
}else{
imgView.topAnchor.constraint(equalTo: mainView.topAnchor , constant: 12).isActive = true
}
lastImage = samsam
mainViewBootom = mainView.bottomAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 12)
mainViewBootom!.isActive = true
}
#objc func didClickedAdd(){
let imgView = UIImageView(frame: CGRect(x: 20, y: 0, width: 30, height: 20))
imgView.backgroundColor = .orange
mainView.addSubview(imgView)
let ss = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 50))
imgView.backgroundColor = .green
mainView.addSubview(ss)
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imgView.widthAnchor.constraint(equalToConstant: 40).isActive = true
imgView.heightAnchor.constraint(equalToConstant: 60).isActive = true
ss.translatesAutoresizingMaskIntoConstraints = false
ss.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = false
ss.widthAnchor.constraint(equalToConstant: 80).isActive = true
ss.heightAnchor.constraint(equalToConstant: 90).isActive = true
if lastImage != nil {
ss.topAnchor.constraint(equalTo: imgView.topAnchor , constant: 20).isActive = true
imgView.topAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 50).isActive = true
}else{
imgView.topAnchor.constraint(equalTo: mainView.topAnchor , constant: 10).isActive = true
ss.bottomAnchor.constraint(equalTo: imgView.bottomAnchor , constant: 25).isActive = true
}
lastImage = imgView
lastImage2 = ss
mainView.removeConstraint(mainViewBootom!)
mainViewBootom = mainView.bottomAnchor.constraint(equalTo: lastImage2!.bottomAnchor , constant: 40)
mainViewBootom!.isActive = true
view.layoutIfNeeded()
scrollView.contentSize = CGSize(width: view.frame.width, height: mainView.frame.height)
view.layoutIfNeeded()
}
}
Couple notes...
With proper constraint setup, auto-layout handles the UIScrollView content size all by itself. No need to ever set scrollView.contentSize = ...
You have several instances of adding a subview (image view) to your mainView, which is a subview of your scroll view, but then you add constraints from that subview to your controller's view. Make sure you are constraining elements to the proper other elements.
Here's your code, with commented changes:
class BenViewController: UIViewController {
fileprivate var lastImage:UIImageView?
// 1) don't need this
// fileprivate var lastImage2:UIImageView?
fileprivate var mainViewBootom:NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupVIew()
}
// 2) don't need this
// override func viewDidAppear(_ animated: Bool) {
// scrollView.contentSize = CGSize(width: view.frame.width, height: mainView.frame.height)
// view.layoutIfNeeded()
// }
//MARK: Components
let scrollView:UIScrollView = {
let sv = UIScrollView(frame: .zero)
return sv
}()
let mainView:UIView = {
let uv = UIView()
uv.backgroundColor = .white
return uv
}()
let btnAdd:UIButton = {
let btn = UIButton(type: .system)
btn.setTitle("Add", for: .normal)
return btn
}()
let textField:UITextField = {
let jake = UITextField()
return jake
}()
//MARK: Setup UI
func setupVIew() {
view.addSubview(scrollView)
view.addSubview(btnAdd)
view.addSubview(textField)
scrollView.translatesAutoresizingMaskIntoConstraints = false
btnAdd.translatesAutoresizingMaskIntoConstraints = false
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
btnAdd.centerXAnchor.constraint(equalTo: view.centerXAnchor),
btnAdd.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -12),
btnAdd.widthAnchor.constraint(equalToConstant: 100),
btnAdd.heightAnchor.constraint(equalToConstant: 45),
//
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
textField.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 25),
textField.widthAnchor.constraint(equalToConstant: 100),
textField.heightAnchor.constraint(equalToConstant: 45),
//
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: btnAdd.topAnchor , constant: -12),
])
btnAdd.addTarget(self, action: #selector(didClickedAdd), for: .touchUpInside)
scrollView.addSubview(mainView)
mainView.translatesAutoresizingMaskIntoConstraints = false
// 3) change this:
// NSLayoutConstraint.activate([
// mainView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
// mainView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// mainView.topAnchor.constraint(equalTo: scrollView.topAnchor),
// ])
//
// to this
NSLayoutConstraint.activate([
mainView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
mainView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
mainView.topAnchor.constraint(equalTo: scrollView.topAnchor),
mainView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
mainView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
])
// end of change 3)
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 100))
imgView.backgroundColor = .red
mainView.addSubview(imgView)
let samsam = UIImageView(frame: CGRect(x: 0, y: 200, width: 40, height: 100))
samsam.backgroundColor = .blue
mainView.addSubview(samsam)
imgView.translatesAutoresizingMaskIntoConstraints = false
// 4) change view.centerXAnchor to mainView.centerXAnchor
// imgView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imgView.centerXAnchor.constraint(equalTo: mainView.centerXAnchor).isActive = true
imgView.widthAnchor.constraint(equalToConstant: 150).isActive = true
imgView.heightAnchor.constraint(equalToConstant: 100).isActive = true
samsam.translatesAutoresizingMaskIntoConstraints = false
// 5) change view.centerXAnchor to mainView.centerXAnchor
// samsam.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
samsam.centerXAnchor.constraint(equalTo: mainView.centerXAnchor).isActive = true
samsam.topAnchor.constraint(equalTo: imgView.bottomAnchor).isActive = true
samsam.widthAnchor.constraint(equalToConstant: 75).isActive = true
samsam.heightAnchor.constraint(equalToConstant: 100).isActive = true
if lastImage != nil {
imgView.topAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 20).isActive = true
}else{
imgView.topAnchor.constraint(equalTo: mainView.topAnchor , constant: 12).isActive = true
}
lastImage = samsam
mainViewBootom = mainView.bottomAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 12)
mainViewBootom!.isActive = true
}
#objc func didClickedAdd(){
let imgView = UIImageView(frame: CGRect(x: 20, y: 0, width: 30, height: 20))
imgView.backgroundColor = .orange
mainView.addSubview(imgView)
let ss = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 50))
// 6) typo or copy/paste mistake
// imgView.backgroundColor = .green
ss.backgroundColor = .green
mainView.addSubview(ss)
imgView.translatesAutoresizingMaskIntoConstraints = false
// 7) change view.centerXAnchor to mainView.centerXAnchor
// imgView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imgView.centerXAnchor.constraint(equalTo: mainView.centerXAnchor).isActive = true
imgView.widthAnchor.constraint(equalToConstant: 40).isActive = true
imgView.heightAnchor.constraint(equalToConstant: 60).isActive = true
ss.translatesAutoresizingMaskIntoConstraints = false
// 8) change view.leadingAnchor to mainView.leadingAnchor
// ss.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = false
ss.leadingAnchor.constraint(equalTo: mainView.leadingAnchor).isActive = false
ss.widthAnchor.constraint(equalToConstant: 80).isActive = true
ss.heightAnchor.constraint(equalToConstant: 90).isActive = true
// 9) always need to do this ... but did you mean imgView.bottomAnchor?
ss.topAnchor.constraint(equalTo: imgView.topAnchor , constant: 20).isActive = true
if lastImage != nil {
// 9a) instead of only here
//ss.topAnchor.constraint(equalTo: imgView.topAnchor , constant: 20).isActive = true
imgView.topAnchor.constraint(equalTo: lastImage!.bottomAnchor , constant: 50).isActive = true
}else{
imgView.topAnchor.constraint(equalTo: mainView.topAnchor , constant: 10).isActive = true
}
// 10) always need to do this
// deactivate bottom constraint
mainViewBootom?.isActive = false
lastImage = ss
mainViewBootom = mainView.bottomAnchor.constraint(equalTo: lastImage!.bottomAnchor, constant: 40)
mainViewBootom?.isActive = true
// 11) don't need any of this
// lastImage = imgView
// lastImage2 = ss
// mainView.removeConstraint(mainViewBootom!)
//
//
// mainViewBootom = mainView.bottomAnchor.constraint(equalTo: lastImage2!.bottomAnchor , constant: 40)
//
//
//
//
// mainViewBootom!.isActive = true
// view.layoutIfNeeded()
//
// scrollView.contentSize = CGSize(width: view.frame.width, height: mainView.frame.height)
// view.layoutIfNeeded()
}
}
Use Xcode’s “view debugger” (the button is circled in red in my screen snapshot below) and you’ll see what’s going on:
Your ss view has no background color. Note, that when you created that view, you accidentally reset the imgView background color a second time rather than setting the ss.backgroundColor.
Fix that and you’ll see your both imgView and ss:
The view debugger is your best friend when trying to diagnose issues like this. Now, obviously, the green view probably isn’t where you intended it, but you should now be able to see it and diagnose that issue very easily.
All of this having been said, a few observations:
You’re making life much harder than you need to. If you just set the constraints for the scroll view and a stack view within that scroll view, you then only need to add an arranged subview. For example:
#objc func didTapButton(_ sender: UIButton) {
stackView.addArrangedSubview(randomView())
stackView.addArrangedSubview(randomView())
}
Note, once the stack view and scroll view have been set up (see below), then you don’t need to mess around with contentSize or constraints for these subviews at all (other than the widthAnchor and heightAnchor). The auto layout engine, combined with the constraints between the stack view and the scroll view, will take care of everything for you.
So, a full working example:
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .center
stackView.spacing = 10
return stackView
}()
let button: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Add", for: .normal)
button.addTarget(self, action: #selector(didTapButton(_:)), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
}
// MARK: - Actions
extension ViewController {
#objc func didTapButton(_ sender: UIButton) {
stackView.addArrangedSubview(randomView())
stackView.addArrangedSubview(randomView())
}
}
// MARK: - Private utility methods
private extension ViewController {
func configure() {
view.addSubview(scrollView)
view.addSubview(button)
scrollView.addSubview(stackView)
NSLayoutConstraint.activate([
// define frame of `scrollView`
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: button.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// define frame of `button`
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.bottomAnchor.constraint(equalTo: view.bottomAnchor),
// define contentSize of `scrollView` based upon size of `stackView`
stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
// but define width of `stackView` relative to the _main view_
stackView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor)
])
button.setContentHuggingPriority(.required, for: .vertical)
}
func randomView() -> UIView {
let widthRange = view.bounds.width * 0.1 ... view.bounds.width * 0.9
let heightRange = view.bounds.width * 0.1 ... view.bounds.width * 0.25
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.widthAnchor.constraint(equalToConstant: .random(in: widthRange)),
view.heightAnchor.constraint(equalToConstant: .random(in: heightRange))
])
view.backgroundColor = UIColor(red: .random(in: 0.25...1), green: .random(in: 0.25...1), blue: .random(in: 0.25...1), alpha: 1)
return view
}
}
Even better, I’d personally set up the scroll view, stack view, button, and all the associated constraints in Interface Builder, and then that hairy configure method in my example goes away completely. It’s fun to learn how to create views programmatically, but in real-world projects, it’s rarely the most productive way to do it. Do programmatic views where needed (e.g. adding arranged subviews to the stack view on the click of a button), but otherwise, for those views that should be there when you first run the app, Interface Builder is worth considering.
E.g. It dramatically reduces the amount of code above, leaving us simply with:
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var stackView: UIStackView!
#IBAction func didTapButton(_ sender: UIButton) {
stackView.addArrangedSubview(randomView())
stackView.addArrangedSubview(randomView())
}
}
// MARK: - Private utility methods
private extension ViewController {
func randomView() -> UIView { ... }
}
Clearly, it takes a while to get used to designing views and configuring constraints in IB, but it’s worth the effort. It distills our code down the the bare essentials.
In your code, you’re setting frames for these image views and then setting translatesAutoresizingMaskIntoConstraints. There’s absolutely no point in setting the frame in that case, because translatesAutoresizingMaskIntoConstraints says “ignore my frame, use constraints instead.”
I’m assuming you’re doing all of this just to become familiar with scroll views, but it’s worth noting that, especially when adding lots of image views, that the scroll view is an inherently inefficient approach.
For example, let’s say you’ve added 100 image views, but you can see only 8 at a time. Do you really want to hold all 100 image views in memory at the same time? No.
But, UITableView, which is a subclass of UIScrollView, takes care of this. You end up only keeping the currently visible image views in memory. It’s a far better approach.
This is especially true when you start using actual UIImage objects, because they require a lot of memory. We get lulled into a sense of security, looking at reasonably sized PNG/JPG assets, but when they’re loaded into memory, they’re uncompressed and require a disproportionate amount of memory.

How to push elements down to stack, Xcode

I want to send message to user, but when I send message it pushing on top of stack, but I need to push it down like telegram or other messengers does.
here is code of stack settings
func setScrollView(){
// messageScrollView.frame = CGRect(x: 0, y: 90, width: self.view.bounds.width, height: CGFloat( self.view.bounds.height))
messageScrollView.translatesAutoresizingMaskIntoConstraints = false
messageScrollView.backgroundColor = UIColor(red:0.93, green:0.94, blue:0.97, alpha:1.0)
messageScrollView.delegate = self
messageScrollView.bottomAnchor.constraint(equalTo: bottomMessager.topAnchor, constant: 0).isActive = true
messageScrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 90).isActive = true
messageScrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
messageScrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
messageScrollView.contentSize = CGSize(width: self.view.bounds.width, height: CGFloat(messageScrollView.bounds.height))
messageScrollView.addSubview(messageStackView)
}
func setStackView(){
messageStackView.axis = .vertical
messageStackView.alignment = .center
messageStackView.distribution = .fillProportionally
messageStackView.spacing = 10
messageStackView.topAnchor.constraint(equalTo: messageScrollView.topAnchor).isActive = true
messageStackView.leftAnchor.constraint(equalTo: messageScrollView.leftAnchor).isActive = true
messageStackView.widthAnchor.constraint(equalTo: messageScrollView.widthAnchor).isActive = true
messageStackView.bottomAnchor.constraint(equalTo: messageScrollView.bottomAnchor, constant: 0).isActive = true
}
and then I create a message and push it into the stack like
let messageView = MessageView(message: message)
messageStackView.addArrangedSubview(messageView)
messageView.setMyMessageView()
you can see the image below, there's messages on the top
how can I add messages on the bottom of stack?
messageStackView.insertArrangedSubview(MessageView(message: message), stackIndex: 0)

Programmatically created ScrollView is not working

i still don't get the hang of UIScrollView...
i want to create one add it to a container and add a StackView to it:
let scroll = UIScrollView()
scroll.contentSize = CGSize(width: stackWidth, height: stackHeight)
bottomContainer.addSubview(scroll)
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .equalSpacing
scroll.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
scroll.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scroll.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: 25),
scroll.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: 25),
scroll.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor),
scroll.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor),
scroll.widthAnchor.constraint(equalToConstant: stackWidth),
scroll.heightAnchor.constraint(equalToConstant: stackWidth),
stack.topAnchor.constraint(equalTo: scroll.topAnchor),
stack.bottomAnchor.constraint(equalTo: scroll.bottomAnchor),
stack.leadingAnchor.constraint(equalTo: scroll.leadingAnchor),
stack.widthAnchor.constraint(equalToConstant: stackWidth),
])
bottomContainer is created in Storyboard.
stackHeight is calculated to be 50 less than the height of bottomContainer and stackWidth is variable but even if gets greater than the bottomContainer it doesn't scroll. Thanks for any help
Try this
var screenHeight = UIScreen.main.bounds.height
var screenWidth = UIScreen.main.bounds.width
let scroll = UIScrollView()
scroll.contentSize = CGSize(width: screenWidth, height: screenHeight)
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .equalSpacing
scroll.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
scroll.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scroll.topAnchor.constraint(equalTo: bottomContainer.topAnchor, constant: 25),
scroll.bottomAnchor.constraint(equalTo: bottomContainer.bottomAnchor, constant: 25),
scroll.leadingAnchor.constraint(equalTo: bottomContainer.leadingAnchor),
scroll.trailingAnchor.constraint(equalTo: bottomContainer.trailingAnchor),
scroll.widthAnchor.constraint(equalToConstant: stackWidth),
scroll.heightAnchor.constraint(equalToConstant: stackWidth),
stack.topAnchor.constraint(equalTo: scroll.topAnchor),
stack.bottomAnchor.constraint(equalTo: scroll.bottomAnchor),
stack.leadingAnchor.constraint(equalTo: scroll.leadingAnchor),
stack.widthAnchor.constraint(equalToConstant: stackWidth),
])
scroll.contentSize = CGSize(width: stackWidth, height: stackHeight)
bottomContainer.addSubview(scroll)