Why is Page Control not reflecting where I am on the UIScrollView? - ios

After editing my UIScrollView size, page control stopped working.
You can see there are only 3 slides. But (1) Page Control isn't reflecting which slide I'm on and (2) I can only scroll from slide 1 to slide 3.
Here's my code:
func setupSlideScrollView(slides : [Slide]) {
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 154)
scrollView.contentSize = CGSize(width: 188 * CGFloat(slides.count) + CGFloat((slides.count - 1) * 10), height: 153)
scrollView.isPagingEnabled = true
var lastCellMaxX: CGFloat = 0
let constantSpacingBetweenCell: CGFloat = 10
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: lastCellMaxX, y: 0, width: 220, height: 153)
scrollView.addSubview(slides[i])
lastCellMaxX += 188 + constantSpacingBetweenCell
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width)
pageControl.currentPage = Int(pageIndex)
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
// This will always round down to zero
// since the contentOffset.x will always be smaller than the frame width...
let pageIndex = round(scrollView.contentOffset.x/scrollView.frame.size.width)
// Possible logic to correct this?
let pageIndex = scrollView.contentOffset.x / (width of a slide)
pageControl.currentPage = Int(pageIndex)
}
-- Updated due to chat --
Your scrollview's frame is fine. However, you need to add a stackview to hold all your slides in order to scroll through it. Scrollviews are a bit tricky since you can't just add views and expect it to be scrollable.
Here is test code I used to create a scrollView that contains stackviews.
func createSlideshow() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
let slide1 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide1.backgroundColor = UIColor.red
let slide2 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide2.backgroundColor = UIColor.blue
let slide3 = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 375))
slide3.backgroundColor = UIColor.yellow
let slides: [UIView] = [slide1, slide2, slide3]
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 10
for slide in slides {
stackView.addArrangedSubview(slide)
slide.widthAnchor.constraint(equalToConstant: slide.frame.width).isActive = true
slide.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true
}
scrollView.addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(greaterThanOrEqualTo: scrollView.widthAnchor).isActive = true
stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
}

Related

Programatically created UISwitch non-responsive

I have created a table that looks like what you see in the screenshot.
Here is the code:
lazy var contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = .white
scrollView.frame = self.view.bounds
scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height * 200)
scrollView.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
scrollView.bounces = true
return scrollView
}()
lazy var containerView : UIView = {
let view = UIView()
view.backgroundColor = .white
view.frame.size = contentSize
return view
}()
let weekStack = UIStackView()
weekStack.axis = .vertical
weekStack.distribution = .fillProportionally
weekStack.spacing = 2
containerView.addSubview(weekStack)
weekStack.translatesAutoresizingMaskIntoConstraints = false
weekStack.topAnchor.constraint(equalTo: restaurantImage.bottomAnchor, constant: 20).isActive = true
weekStack.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor, constant: 20).isActive = true
weekStack.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
let arrayOfDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
for index in 0...arrayOfDays.count - 1 {
let dayStack = UIStackView()
weekStack.addArrangedSubview(dayStack)
dayStack.axis = .horizontal
dayStack.distribution = .fillEqually
dayStack.spacing = 4
let daySwitch = UISwitch(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
dayStack.addArrangedSubview(daySwitch)
let dayLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 0))
dayLabel.text = arrayOfDays[index]
dayLabel.textAlignment = .center
dayLabel.font = UIFont(name: "NexaLight", size: 16)
dayStack.addArrangedSubview(dayLabel)
let startTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
startTextField.placeholder = "Open"
startTextField.textAlignment = .center
startTextField.delegate = self
startTextField.text = "9"
startTextField.font = UIFont(name: "NexaLight", size: 16)
dayStack.addArrangedSubview(startTextField)
startTextField.inputView = timePicker
startTextField.inputAccessoryView = toolbar
let closeTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
closeTextField.placeholder = "Close"
closeTextField.textAlignment = .center
closeTextField.text = "23"
closeTextField.font = UIFont(name: "NexaLight", size: 16)
closeTextField.delegate = self
dayStack.addArrangedSubview(closeTextField)
closeTextField.inputView = timePicker
closeTextField.inputAccessoryView = toolbar
}
The problem is that the last 2 switches are not responding as shown in the screenshot. I cannot turn them on. I also cannot interact with the last 2 rows of text fields where you see "9" and "23". This is from the simulator by the way.

Bottom border for text field doesn’t appear

I tried to add a bottom border to my text field but it doesn't work. I know that there are similar questions out there but none of those answers help. Also, I removed this line of code below and tried because there is no border by default, it still doesn't work:
username.borderStyle = UITextField.BorderStyle.none
Here is the whole code:
class SignUpScreen: UIViewController {
let username = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(username)
// Background color
view.backgroundColor = .white
username.placeholder = "Name"
username.borderStyle = UITextField.BorderStyle.none
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0, y: view.frame.height - 1, width: view.frame.width, height: 1.0)
bottomLine.backgroundColor = UIColor.black.cgColor
username.layer.addSublayer(bottomLine)
username.translatesAutoresizingMaskIntoConstraints = false
username.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
username.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
username.widthAnchor.constraint(equalToConstant: 150).isActive = true
username.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}
Hope someone can help me out! Thanks! :)
Here is what you were missing: You were using the main view's frame for creating the frame of your layer. You must use the text field.
Also first draw your text field properly with constraints then add layer to text field.
In viewDidLoad your content view is loaded to main memory. There is no frame assignment in that method. So use viewWillAppear or viewDidAppear.
Now when your view will appear every time a new TextField & a layer will be added. So you need to make a check to restrict that behaviour. E.g if a text field is already added to your view then don't add.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.addSubview(username)
/*
* Create the text field
*/
view.backgroundColor = .white
username.placeholder = "Name"
username.borderStyle = UITextField.BorderStyle.none
username.translatesAutoresizingMaskIntoConstraints = false
username.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
username.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
username.widthAnchor.constraint(equalToConstant: 300).isActive = true
username.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
/*
* Here add the shap layer
*/
let bottomLine = CALayer()
/*
* Here is what you were missing.
* You were using the main view's frame instead of your textfield
*/
bottomLine.frame = CGRect(x: 0, y: username.bounds.height - 1, width: username.bounds.width, height: 1.0)
bottomLine.backgroundColor = UIColor.black.cgColor
username.layer.addSublayer(bottomLine)
}
bottomLine.frame = CGRect(x: 0, y: view.frame.height - 1, width: view.frame.width, height: 1.0)
you must use username.bounds, instead of view.frame
let border = CALayer()
let width = CGFloat(3.0)
border.borderColor = UIColor.black.cgColor
border.frame = CGRect(x: 0, y: textFieldOutlet.frame.size.height - width, width: textFieldOutlet.frame.size.width, height: textFieldOutlet.frame.size.height)
border.borderWidth = width
textFieldOutlet.layer.addSublayer(border)
textFieldOutlet.layer.masksToBounds = true
rather than adding a layer maybe you should add your border as UIView and bring it to top also set your textField bgColor as clearColor:
class SignUpScreen: UIViewController {
let username = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(username)
// Background color
view.backgroundColor = .white
username.placeholder = "Name"
username.borderStyle = UITextField.BorderStyle.none
// make sure your textField doesn't have back ground
username.backgroundColor = .clear
let bottomLine = UIView()
bottomLine.frame = CGRect(x: 0, y: view.frame.height - 1, width: view.frame.width, height: 1.0)
bottomLine.backgroundColor = UIColor.black.cgColor
// be sure you bring it to top
self.view.layer.insertSublayer(bottomLine, at:0)
username.translatesAutoresizingMaskIntoConstraints = false
username.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
username.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
username.widthAnchor.constraint(equalToConstant: 150).isActive = true
username.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}
Try this
func bottomBorderTextField(_ textField: UIView, color: UIColor) {
// For Bottom Border
let bottomLayer = CALayer()
let frame = viewType.frame
bottomLayer.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width - 2, height: 0.5)
bottomLayer.backgroundColor = color.cgColor
viewType.layer.addSublayer(bottomLayer)
}
In viewDidload()
self.bottomBorderTextField(self.txtField, color: yourTextColor)

Problem when inserting a sublayer below an existing layer in Swift?

I'm trying to add a sublayer behind an existing layer in Swift, but the sublayer is still coming up in front of the existing layer - I must have a problem in my code;
import UIKit
class ViewController: UIViewController {
let mainView = UIView()
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let focusBG = UIView()
override func viewDidLoad() {
super.viewDidLoad()
mainView.backgroundColor = UIColor.gray
view.addSubview(mainView)
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.widthAnchor.constraint(equalToConstant: 325).isActive = true
mainView.heightAnchor.constraint(equalToConstant: ((325 / 9) * 16)).isActive = true
mainView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
mainView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
let tapView = UIView(frame: CGRect(x: 50, y: 0, width: 150, height: 200))
tapView.backgroundColor = UIColor.red
mainView.addSubview(tapView)
focusBG.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
focusBG.backgroundColor = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 0.4)
self.view.layer.insertSublayer(focusBG.layer, below: tapView.layer)
}
}
Ideally the red box would be in front of the greyed out layer - but this is what i am getting;
Thanks!
Update: Working Code
self.mainView.insertSubview(focusBG, belowSubview: tapView)
focusBG.translatesAutoresizingMaskIntoConstraints = false
focusBG.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
focusBG.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
focusBG.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true
focusBG.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
You can try
self.mainView.insertSubview(focusBG, belowSubiew: tapView)
Or
self.mainView.layer.insertSublayer(focusBG.layer, below: tapView.layer) // not tested
Try using insertSublayer, method works for me.
self.mainView.layer.insertSublayer(your_Layer, at: 1) // 1 is the position of the layer you want to add to the mainView.
Thanks and let me know if this works for you. Dont Forget to upvote if it does ;)

ScrollView snap to center

I want to setup my scrollView like this video (I know in video use collectionview bu for some reason I want convert this effect to scrollView)
https://www.dropbox.com/s/kj6xgj68gz6258p/ScreenRecording_06-26-2018%2019-15-43.MP4
3 important thing:
scroll must snap to center when scrolling
resize current item (forward item is bigger than backward item)
swift
UPDATE:
var ScrollView = UIScrollView()
var arr : Array<UIColor> = [.red,.blue,.green]
override func viewDidLoad() {
super.viewDidLoad()
ScrollView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(ScrollView)
ScrollView.widthAnchor.constraint(equalToConstant: self.view.frame.size.width).isActive = true
ScrollView.heightAnchor.constraint(equalToConstant: 320).isActive = true
ScrollView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive = true
ScrollView.alwaysBounceVertical = false
ScrollView.isPagingEnabled = true
ScrollView.contentSize = CGSize(width: 3.0 * self.view.frame.size.width, height: 320)
ScrollView.contentOffset = CGPoint(x: view.frame.size.width, y: 0)
ScrollView.center = self.view.center
for i in 0..<3 {
let viewBG = UIView()
viewBG.backgroundColor = arr[i]
if (i == 0) {
viewBG.frame = CGRect(x: view.frame.size.width * CGFloat(i) + 125, y: 0, width: view.frame.size.width - 100, height: 320)
} else if(i == 1) {
viewBG.frame = CGRect(x: view.frame.size.width * CGFloat(i) + 50, y: 0, width: view.frame.size.width - 100, height: 320)
} else {
viewBG.frame = CGRect(x: view.frame.size.width * CGFloat(i) - 25, y: 0, width: view.frame.size.width - 100, height: 320)
}
ScrollView.addSubview(viewBG)
}
}
thanks guys
Use iCarousal. It is easy to implement and Swift example is also available.
Following is link -
https://github.com/nicklockwood/iCarousel

Custom titleView changes location after push and pop new screen in stack

I'm trying to implement custom titleView for navigation controller with "title" and "description" labels. If I placed this titleView on first VC, it looks good. If I push second VC into navigation stack and pop it, location of the titleView is changed.
titleView's constraints:
titleLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
descriptionLabel.widthAnchor.constraint(equalTo: titleLabel.widthAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 2.0).isActive = true
In viewDidLoad of VC I use follow code to insert titleView:
navigationItem.titleView = BarTitleView()
navigationItem.titleView?.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
navigationItem.titleView?.updateConstraints()
I tried to insert follow lines into viewWillAppear (second VC has different bar buttons and it can be root of problem), but nothing changes
navigationItem.titleView?.bounds = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
navigationItem.titleView?.updateConstraints()
How can I fixed this issue?
I have created a Title and Subtitle in the Navigation bar without the need for Interface Builder and constraint modification.
My Function to create the title view looks as follows:
class func setTitle(title:String, subtitle:String) -> UIView {
let titleLabel = UILabel(frame: CGRect(x: 0, y: -8, width: 0, height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
titleLabel.text = title
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 12, width: 0, height: 0))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = UIColor.white
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
// Fix incorrect width bug
if (subtitleLabel.frame.size.width > titleLabel.frame.size.width) {
var titleFrame = titleLabel.frame
titleFrame.size.width = subtitleLabel.frame.size.width
titleLabel.frame = titleFrame
titleLabel.textAlignment = .center
}
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: titleLabel.frame.size.width, height: titleLabel.frame.size.height))
titleView.addSubview(titleLabel)
titleView.addSubview(subtitleLabel)
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff < 0 {
let newX = widthDiff / 2
subtitleLabel.frame.origin.x = abs(newX)
} else {
let newX = widthDiff / 2
titleLabel.frame.origin.x = newX
}
return titleView
}
Then to use the title view in any view controller I just call this line:
self.navigationItem.titleView = Functions.Views.setTitle(title: "Title String", subtitle: "Subtitle String")

Resources