Proper way to set UIScrollView with constraints programmatically? - ios

I'm trying to create a simple horizontal scroll between two view controllers positioned side by side programmatically using constraints. What I have here appears to work but everything I've read says that I don't need to configure the size of the contentSize if the constraints are set correctly--autolayout will do that for me. But when I remove scrollView.contentSize = CGSize(width: view.bounds.width * 2, height: view.bounds.height) from viewWillLayoutSubviews, it doesn't scroll. Where did I go wrong?
class ViewController0: UIViewController {
let scrollView = UIScrollView()
let contentView = UIView()
let page1 = ViewController1()
let page2 = ViewController2()
override func loadView() {
setView()
addScrollView()
fillScrollView()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.contentSize = CGSize(width: view.bounds.width * 2, height: view.bounds.height)
}
func setView() {
view = UIView()
view.frame = UIScreen.main.bounds
view.backgroundColor = UIColor.blue
}
func addScrollView() {
scrollView.bounces = false
scrollView.isPagingEnabled = true
scrollView.backgroundColor = UIColor.brown
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
contentView.backgroundColor = UIColor.green
contentView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(contentView)
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
contentView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true
contentView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 2).isActive = true
}
func fillScrollView() {
addChildViewController(page1)
page1.didMove(toParentViewController: self)
page1.view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(page1.view)
page1.view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
page1.view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
page1.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
page1.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true
addChildViewController(page2)
page2.didMove(toParentViewController: self)
page2.view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(page2.view)
page2.view.leadingAnchor.constraint(equalTo: page1.view.trailingAnchor).isActive = true
page2.view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
page2.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
page2.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true
}
}

this should work
class ViewController0: UIViewController {
let scrollView = UIScrollView()
let page1 = ViewController1()
let page2 = ViewController1()
override func loadView() {
setView()
addScrollView()
setupPage()
}
func setView() {
view = UIView()
view.frame = UIScreen.main.bounds
view.backgroundColor = UIColor.blue
}
func addScrollView() {
scrollView.backgroundColor = UIColor.brown
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setupPage() {
page1.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(page1.view)
addChildViewController(page1)
page1.didMove(toParentViewController: self)
page2.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(page2.view)
addChildViewController(page2)
page2.didMove(toParentViewController: self)
let views: [String: UIView] = ["view": view, "page1": page1.view, "page2": page2.view]
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[page1(==view)]|", options: [], metrics: nil, views: views)
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[page1(==view)][page2(==view)]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views)
NSLayoutConstraint.activate(verticalConstraints + horizontalConstraints)
}
}

Related

How to add UIView Gesture - Programmatically UIView

I have searched a lot about adding a gesture on UIView when it is tapped. There are many solutions but none of them worked for me.
I have made UIView class programmatically and using the view in different classes.
Here is my class of UIView:
class PaymentServiceView: UIView {
private let views: UIView = {
let view = UIView()
view.backgroundColor = .white
// view.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
view.layer.borderColor = UIColor.gray.cgColor
view.layer.shadowOpacity = 0.3
view.layer.shadowColor = UIColor.gray.cgColor
view.layer.shadowRadius = 10
view.layer.borderWidth = 0.1
view.layer.cornerRadius = 20
view.isUserInteractionEnabled = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let titleLbl: UILabel = {
var label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.textColor = UIColor.black
label.font = UIFont(name: AppFontName.circularStdRegular, size: 18)
label.clipsToBounds = true
return label
}()
private let subLbl: UILabel = {
var label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.textColor = UIColor.gray
label.numberOfLines = 0
label.textAlignment = .left
label.font = UIFont(name: AppFontName.robotoRegular, size: 15)
label.clipsToBounds = true
return label
}()
private let image: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let btnImage: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.image = UIImage(named: IconName.chevron_down)?.transform(withNewColor: UIColor.btnGray)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
init(titleLabel: String, subTitleLabel: String, imageName: String) {
super.init(frame: CGRect.zero)
self.addSubview(views)
self.views.addSubview(btnImage)
self.views.addSubview(titleLbl)
self.views.addSubview(image)
self.views.addSubview(subLbl)
titleLbl.text = titleLabel
image.image = UIImage(named: imageName)
subLbl.text = subTitleLabel
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
self.views.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.views.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.views.heightAnchor.constraint(equalToConstant: 150).isActive = true
self.views.widthAnchor.constraint(equalToConstant: 320).isActive = true
self.image.centerYAnchor.constraint(equalTo: self.views.centerYAnchor).isActive = true
self.image.leadingAnchor.constraint(equalTo: self.views.leadingAnchor, constant: 15).isActive = true
self.image.widthAnchor.constraint(equalToConstant: 30).isActive = true
self.image.heightAnchor.constraint(equalToConstant: 30).isActive = true
self.titleLbl.centerYAnchor.constraint(equalTo: self.views.centerYAnchor, constant: -35).isActive = true
self.titleLbl.leadingAnchor.constraint(equalTo: image.trailingAnchor, constant: 15).isActive = true
self.subLbl.topAnchor.constraint(equalTo: titleLbl.bottomAnchor, constant: 5).isActive = true
self.subLbl.leadingAnchor.constraint(equalTo: image.trailingAnchor, constant: 15).isActive = true
self.subLbl.trailingAnchor.constraint(equalTo: btnImage.leadingAnchor, constant: -15).isActive = true
btnImage.topAnchor.constraint(equalTo: views.topAnchor, constant: 55).isActive = true
btnImage.rightAnchor.constraint(equalTo: views.rightAnchor, constant: -10).isActive = true
btnImage.heightAnchor.constraint(equalToConstant: 10).isActive = true
}
}
Now Im using this UIView class in PaymentServicesViewController
class PaymentServicesViewController: UIViewController {
private (set) lazy var headerView: HeaderView = { [unowned self] in
let view = HeaderView.init(titleLbl: Headings.paymentService, closeAction: {
self.navigationController?.popViewController(animated: true)
}, nextAction: {
print("next")
}, previousAction: {
self.navigationController?.popViewController(animated: true)
})
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let fundTransferView: PaymentServiceView = {
let view = PaymentServiceView(titleLabel: Headings.fundTransfer, subTitleLabel: Description.fundTransferDecription , imageName: IconName.fundImage )
view.isUserInteractionEnabled = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let subscriptionView: PaymentServiceView = {
let view = PaymentServiceView(titleLabel: Headings.subscribe, subTitleLabel: Description.subscriptionDescription, imageName: IconName.subImage )
view.isUserInteractionEnabled = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private let billPaymentView: PaymentServiceView = {
let view = PaymentServiceView(titleLabel: Headings.billPayment, subTitleLabel: Description.billPaymentDescription , imageName: IconName.billImage )
view.isUserInteractionEnabled = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .gray2
let fundtrasnferGesture = UITapGestureRecognizer(target: self, action: #selector(fundTranferTapped))
fundTransferView.isUserInteractionEnabled = true
self.fundTransferView.addGestureRecognizer(fundtrasnferGesture)
let subscribeGesture = UITapGestureRecognizer(target: self, action: #selector(subscribeTapped))
subscriptionView.isUserInteractionEnabled = true
self.subscriptionView.addGestureRecognizer(subscribeGesture)
let billPaymentGesture = UITapGestureRecognizer(target: self, action: #selector(billPaymentTapped))
fundTransferView.isUserInteractionEnabled = true
self.billPaymentView.addGestureRecognizer(billPaymentGesture)
view.addSubview(headerView)
view.addSubview(subscriptionView)
view.addSubview(fundTransferView)
view.addSubview(billPaymentView)
setupConstraint()
}
#objc func fundTranferTapped(sender: UITapGestureRecognizer) {
print("FundTransfer Tapped.")
}
#objc func subscribeTapped(sender: UITapGestureRecognizer) {
print("Subscribe Tapped.")
}
#objc func billPaymentTapped(sender: UITapGestureRecognizer) {
print("BillPayment Tapped.")
}
private func setupConstraint() {
headerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
headerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
subscriptionView.trailingAnchor.constraint(equalTo: fundTransferView.trailingAnchor, constant: 0).isActive = true
subscriptionView.leadingAnchor.constraint(equalTo: fundTransferView.leadingAnchor, constant: 0).isActive = true
subscriptionView.bottomAnchor.constraint(equalTo: fundTransferView.topAnchor, constant: -130).isActive = true
fundTransferView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
fundTransferView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
billPaymentView.leadingAnchor.constraint(equalTo: fundTransferView.leadingAnchor, constant: 0).isActive = true
billPaymentView.trailingAnchor.constraint(equalTo: fundTransferView.trailingAnchor).isActive = true
billPaymentView.topAnchor.constraint(equalTo: fundTransferView.bottomAnchor, constant: 130).isActive = true
}
}
I know there is a small mistake I'm doing but not sure. Help would be appreciated, Thank you.
You are missing a couple constraints...
If you add this at the end of viewDidLoad():
subscriptionView.clipsToBounds = true
fundTransferView.clipsToBounds = true
billPaymentView.clipsToBounds = true
You'll see that the views "disappear":
because they have no Width or Height constraints (so their size is .zero).
In setupConstraints() in your PaymentServiceView class, add these two lines:
self.widthAnchor.constraint(equalTo: self.views.widthAnchor).isActive = true
self.heightAnchor.constraint(equalTo: self.views.heightAnchor).isActive = true
Now, the PaymentServiceView will be the same Width and Height as self.views view.
However, now that the views have Heights:
your layout needs to be adjusted.
Change the .clipsToBounds back to false (remove those added lines) so the shadows won't be clipped, and change these constraints in your controller (adjust the 15 and -15 to your liking):
//subscriptionView.bottomAnchor.constraint(equalTo: fundTransferView.topAnchor, constant: -130).isActive = true
subscriptionView.bottomAnchor.constraint(equalTo: fundTransferView.topAnchor, constant: 15).isActive = true
//billPaymentView.topAnchor.constraint(equalTo: fundTransferView.bottomAnchor, constant: 130).isActive = true
billPaymentView.topAnchor.constraint(equalTo: fundTransferView.bottomAnchor, constant: -15).isActive = true
and we get:
Now, because the views have a size, the Tap Gestures will work.

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

scrollview not working if translatesAutoresizingMaskIntoConstraints = false

I have some issues using translatesAutoresizingMaskIntoConstraints.
I am creating a scrollview where you can swipe to the left or right. Every time you get a another image. But for some reason I can't swipe if translatesAutoresizingMaskIntoConstraints = false.
This is with translatesAutoresizingMaskIntoConstraints = false (in this case, I can't swipe left or right)
But if I set translatesAutoresizingMaskIntoConstraints = true it look like this and I can swipe to the left and right. The problem is, that the layout is messed up.
My code:
var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.alwaysBounceVertical = false
scrollView.alwaysBounceHorizontal = false
scrollView.isPagingEnabled = true
return scrollView
}()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.frame = contentView.frame
contentView.addSubview(scrollView)
scrollView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
scrollView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true
scrollView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
}
var frame = CGRect.zero
func viewTutorial() {
for i in 0..<arrayOfTutorilImages.count {
frame.origin.x = scrollView.frame.size.width * CGFloat((i))
frame.size = scrollView.frame.size
let imageView = UIImageView(frame: frame)
imageView.image = UIImage(named: arrayOfTutorilImages[i])
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
imageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true
imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
}
scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(arrayOfTutorilImages.count)), height: scrollView.frame.size.height)
scrollView.delegate = self
}
extension TutorialViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
pageControl.currentPage = Int(pageNumber)
}
}
You need to add constraints probably , You can try
class TutorialViewController: UIViewController {
var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.alwaysBounceVertical = false
scrollView.alwaysBounceHorizontal = false
scrollView.isPagingEnabled = true
return scrollView
}()
override func viewDidLoad() {
super.viewDidLoad()
contentView.addSubview(scrollView)
scrollView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
scrollView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true
scrollView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true
viewTutorial()
}
func viewTutorial() {
var con:UIView = scrollView
for i in 0..<arrayOfTutorilImages.count {
let imageView = UIImageView(frame: CGRect.zero)
imageView.image = UIImage(named: arrayOfTutorilImages[i])
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.addSubview(imageView)
if con == scrollView {
imageView.leftAnchor.constraint(equalTo: con.leftAnchor, constant: 0).isActive = true
}
else {
imageView.leftAnchor.constraint(equalTo: con.rightAnchor, constant: 0).isActive = true
}
imageView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
if i == arrayOfTutorilImages.count - 1 {
imageView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0).isActive = true
}
imageView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true
con = imageView
}
scrollView.delegate = self
}
}
extension TutorialViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
}
}
Don't set frames when using constrraints
Add Scrollview frame when create
var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame:.zero)
//other properties
return scrollView
}()
ImageView constraints same as for ScrollView.
That is the reason why you can't swipe, because all your images have the same constraints, and they are located one over another.
You should do smth like:
imageView.translatesAutoresizingMaskIntoConstraints = true
imageView.frame.size = contentView.frame.size
imageView.frame.origin = CGPoint(x: imageIndex * contentView.frame.size.width, y: 0.0)

removing specific customview,uiview,textview,etc from viewcontroller

what i am trying to do is simple. let me explain what i have first, in the mainviewcontroller i have 3 main view at the beginning navbar, content,and bottombtn. i have a sidebar btn that then trigger a function in the mainviewcontroller, each function is suppose to remove the middle view (the content) and then place a new subview to take the content place.
the problem: it work at first the function delete contentTxt and replace it with one of the new view example: connectView, but the problem is when i try to trigger another function let say addAchievementView() it will not delete connectView and then add achievementview instead it let add achievementview below the connect View
my Goal: is for the function to delete the previous view(whichever view that is taking the contentplace) and then adding a new view. is there a way to get around this? or is there a better way to do this?
here is the mainViewController code:
class mainViewController: UIViewController {
let navbar:navbarView = {
let content = navbarView()
return content
}()
let contentTxt:UITextView = {
let content = UITextView()
content.backgroundColor = UIColor.green
content.font = UIFont(name: "copperplate", size: 20)
return content
}()
let bottomBtn:UIButton = {
let content = UIButton()
content.backgroundColor = UIColor.blue
return content
}()
override func viewDidLoad() {
super.viewDidLoad()
navbar.translatesAutoresizingMaskIntoConstraints = false
contentTxt.translatesAutoresizingMaskIntoConstraints = false
bottomBtn.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(navbar)
view.addSubview(contentTxt)
view.addSubview(bottomBtn)
navbar.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
navbar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
navbar.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
navbar.heightAnchor.constraint(equalToConstant: 50).isActive = true
contentTxt.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
contentTxt.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
contentTxt.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
contentTxt.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
bottomBtn.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant:-10).isActive = true
bottomBtn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
bottomBtn.widthAnchor.constraint(equalToConstant: 70).isActive = true
bottomBtn.heightAnchor.constraint(equalToConstant: 70).isActive = true
}
#objc func addConnectView(){
print("addConnectView")
self.contentTxt.removeFromSuperview()
let connect:connectView = {
let content = connectView()
content.backgroundColor = UIColor.red
return content
}()
connect.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(connect)
self.view.sendSubview(toBack: connect)
connect.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
connect.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
connect.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
connect.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addTemplateView(){
print("addTemplateView")
self.contentTxt.removeFromSuperview()
let content:templateView = {
let content = templateView()
content.backgroundColor = UIColor.blue
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addSettingView(){
print("addSettingView")
self.contentTxt.removeFromSuperview()
let content:settingView = {
let content = settingView()
content.backgroundColor = UIColor.green
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addAchievementView(){
print("addAchievementView")
self.contentTxt.removeFromSuperview()
let content:achievementView = {
let content = achievementView()
content.backgroundColor = UIColor.gray
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addCommandView(){
print("addCommandView")
self.contentTxt.removeFromSuperview()
let content:commandView = {
let content = commandView()
content.backgroundColor = UIColor.cyan
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addListView(){
print("addListView")
self.contentTxt.removeFromSuperview()
let content:commandView = {
let content = commandView()
content.backgroundColor = UIColor.red
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func addNavbarView(){
print("addNavbarView")
self.contentTxt.removeFromSuperview()
let content:navbarListView = {
let content = navbarListView()
content.backgroundColor = UIColor.red
return content
}()
content.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(content)
self.view.sendSubview(toBack: content)
content.topAnchor.constraint(equalTo: navbar.bottomAnchor, constant: 5).isActive = true
content.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
content.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
content.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
}
#objc func sideController(){
let next = self.storyboard?.instantiateViewController(withIdentifier: "sideViewController") as! sideViewController
self.present(next, animated: true, completion: nil)
}
#objc func profileController(){
let next = self.storyboard?.instantiateViewController(withIdentifier: "profileViewController") as! profileViewController
self.present(next, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Before add any view make sure to remove all other , as you don't know what is currently displayed so
self.contentTxt.removeFromSuperview()
self.content.removeFromSuperview() //
self.content.removeFromSuperview() // for settings
Also this line is the problem
self.view.sendSubview(toBack: content)
as by default the added view is placed above all childs of the parentView
I vote for creating placeHolderView and remove it's subviews before any addition , this will prevent headache of knowing which one is currently displayed , or you may give a tag to any added view and do this before any new addition
self.view.subviews.forEach { if $0.tag == 11 {
$0.removeFromSuperview()
}}

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