Beginner here with a beginner question:
I have 3 segmented controls in my view controller and I have 3 nearly identical functions that sets their colors/styling/animation. I know I shouldn't repeat code, but I'm not entirely sure how to combine these. It's prob something obvious but I need to see it done so I can do it other parts of my app. Could someone show me for this example:
class Example: UIViewController {
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var textSegmentedControl: UISegmentedControl!
#IBOutlet weak var translationSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
setMainSegmentedControlStyle()
setTextSegmentedControlStyle()
setTranslationSegmentedControlStyle()
}
func setTextSegmentedControlStyle() {
textSegmentedControl.backgroundColor = .clear
textSegmentedControl.tintColor = .clear
textSegmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16), NSAttributedStringKey.foregroundColor: UIColor.lightGray
], for: .normal)
textSegmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16),
NSAttributedStringKey.foregroundColor: UIColor.darkGray
], for: .selected)
let textSegmentedUnderline = UIView()
textSegmentedUnderline.translatesAutoresizingMaskIntoConstraints = false // false since we are using auto layout constraints
textSegmentedUnderline.backgroundColor = #colorLiteral(red: 0.992502749, green: 0.532302916, blue: 0.08773707598, alpha: 1)
view.addSubview(textSegmentedUnderline)
textSegmentedUnderline.topAnchor.constraint(equalTo: textSegmentedControl.bottomAnchor).isActive = true
textSegmentedUnderline.heightAnchor.constraint(equalToConstant: 3).isActive = true
textSegmentedUnderline.leftAnchor.constraint(equalTo: textSegmentedControl.leftAnchor).isActive = true
textSegmentedUnderline.widthAnchor.constraint(equalTo: textSegmentedControl.widthAnchor, multiplier: 1 / CGFloat(textSegmentedControl.numberOfSegments)).isActive = true
UIView.animate(withDuration: 0.3) {
self.textSegmentedUnderline.frame.origin.x = (self.textSegmentedControl.frame.width / CGFloat(self.textSegmentedControl.numberOfSegments)) * CGFloat(self.textSegmentedControl.selectedSegmentIndex)
}
}
func setTranslationSegmentedControlStyle() {
translationSegmentedControl.backgroundColor = .clear
translationSegmentedControl.tintColor = .clear
translationSegmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16), NSAttributedStringKey.foregroundColor: UIColor.lightGray
], for: .normal)
translationSegmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16), NSAttributedStringKey.foregroundColor: UIColor.darkGray
], for: .selected)
let translationSegmentedUnderline = UIView()
translationSegmentedUnderline.translatesAutoresizingMaskIntoConstraints = false // false since we are using auto layout constraints
translationSegmentedUnderline.backgroundColor = #colorLiteral(red: 0.992502749, green: 0.532302916, blue: 0.08773707598, alpha: 1)
view.addSubview(translationSegmentedUnderline)
translationSegmentedUnderline.topAnchor.constraint(equalTo: textSegmentedControl.bottomAnchor).isActive = true
translationSegmentedUnderline.heightAnchor.constraint(equalToConstant: 3).isActive = true
translationSegmentedUnderline.leftAnchor.constraint(equalTo: translationSegmentedControl.leftAnchor).isActive = true
translationSegmentedUnderline.widthAnchor.constraint(equalTo: translationSegmentedControl.widthAnchor, multiplier: 1 / CGFloat(translationSegmentedControl.numberOfSegments)).isActive = true
UIView.animate(withDuration: 0.3) {
self.translationSegmentedUnderline.frame.origin.x = (self.textSegmentedControl.frame.width / CGFloat(self.translationSegmentedControl.numberOfSegments)) * CGFloat(self.translationSegmentedControl.selectedSegmentIndex)
}
}
func setMainSegmentedControlStyle() {
segmentedControl.backgroundColor = .clear
segmentedControl.tintColor = .clear
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16), NSAttributedStringKey.foregroundColor: UIColor.lightGray
], for: .normal)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16),
NSAttributedStringKey.foregroundColor: UIColor.darkGray
], for: .selected)
let buttonBar = UIView()
buttonBar.translatesAutoresizingMaskIntoConstraints = false // false since we are using auto layout constraints
buttonBar.backgroundColor = #colorLiteral(red: 0.992502749, green: 0.532302916, blue: 0.08773707598, alpha: 1)
view.addSubview(buttonBar)
buttonBar.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor).isActive = true
buttonBar.heightAnchor.constraint(equalToConstant: 3).isActive = true
buttonBar.leftAnchor.constraint(equalTo: segmentedControl.leftAnchor).isActive = true
buttonBar.widthAnchor.constraint(equalTo: segmentedControl.widthAnchor, multiplier: 1 / CGFloat(segmentedControl.numberOfSegments)).isActive = true
UIView.animate(withDuration: 0.3) {
self.buttonBar.frame.origin.x = (self.segmentedControl.frame.width / CGFloat(self.segmentedControl.numberOfSegments)) * CGFloat(self.segmentedControl.selectedSegmentIndex)
}
}
}
If all the styling code is exactly the same, you can declare a function that accepts a control as an argument:
func style(control: UISegmentedControl) {
control.backgroundColor = .clear
// continue styling here
}
Then simply call that function however many times you need, passing in each control:
style(control: segmentedControl)
style(control: textSegmentedControl)
style(control: translationSegmentedControl)
Note, though, that you should set as much as you can (such as backgroundColor) in your Storyboard rather than code.
Related
I have an app which displays a list of fruits. When you click on one of them, a view pops up with all the information and nutritional values within that fruit. If the fruit I click on contains more than 10 in sugar, the background should repeat between red and white. My problem is that I have a back button (Tilbake) which works on every view except for the ones that have the animated background color with over 10 in sugar. The ability to swipe the view down stops working too. It seems to be some kind of layer which is on top of the screen stopping me from actually touching the screen. How do I solve this ?
import UIKit
class FruitDetailVC: UIViewController{
var fruit: Fruit?
var safeArea: UILayoutGuide!
let nameLabel = UILabel()
let genusLabel = UILabel()
let familyLabel = UILabel()
let orderLabel = UILabel()
let idLabel = UILabel()
let carbLabel = UILabel()
let proteinLabel = UILabel()
let fatLabel = UILabel()
let caloriesLabel = UILabel()
let sugarLabel = UILabel()
let dividerLabel = UILabel()
let sugarWarningLabel = UILabel()
let dismissButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
setupdata()
setupLabel()
setupDismissButton()
safeArea = view.layoutMarginsGuide
view.backgroundColor = .white
if (fruit?.nutritions.sugar)! > 10{
sugarWarningLabel.text = "This contains over 10 of sugar!!!"
animatedBackground()
}
}
func animatedBackground(){
UIView.animate(withDuration: 1.0, delay: 0.0, options:[.repeat, .autoreverse], animations: {
self.view.backgroundColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0)
}, completion:{
(completed : Bool) -> Void in
UIView.animate(withDuration: 1.0, delay: 0.0, options:[.repeat, .autoreverse], animations: {
self.view.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
}, completion:nil)
})
}
func setupLabel(){
view.addSubview(nameLabel)
view.addSubview(genusLabel)
view.addSubview(familyLabel)
view.addSubview(orderLabel)
view.addSubview(idLabel)
view.addSubview(carbLabel)
view.addSubview(proteinLabel)
view.addSubview(fatLabel)
view.addSubview(caloriesLabel)
view.addSubview(sugarLabel)
view.addSubview(dividerLabel)
view.addSubview(sugarWarningLabel)
//General infromation about selected fruit
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
nameLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
nameLabel.font = UIFont(name: "Verdana-Bold", size: 16)
genusLabel.translatesAutoresizingMaskIntoConstraints = false
genusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
genusLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor).isActive = true
genusLabel.font = UIFont(name: "Verdana", size: 14)
familyLabel.translatesAutoresizingMaskIntoConstraints = false
familyLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
familyLabel.topAnchor.constraint(equalTo: genusLabel.bottomAnchor).isActive = true
familyLabel.font = UIFont(name: "Verdana", size: 14)
orderLabel.translatesAutoresizingMaskIntoConstraints = false
orderLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
orderLabel.topAnchor.constraint(equalTo: familyLabel.bottomAnchor).isActive = true
orderLabel.font = UIFont(name: "Verdana", size: 14)
idLabel.translatesAutoresizingMaskIntoConstraints = false
idLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
idLabel.topAnchor.constraint(equalTo: orderLabel.bottomAnchor).isActive = true
idLabel.font = UIFont(name: "Verdana", size: 14)
//Nutrition information divider
dividerLabel.translatesAutoresizingMaskIntoConstraints = false
dividerLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
dividerLabel.topAnchor.constraint(equalTo: idLabel.bottomAnchor).isActive = true
dividerLabel.font = UIFont(name: "Verdana-Bold", size: 16)
//Nutrition information
carbLabel.translatesAutoresizingMaskIntoConstraints = false
carbLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
carbLabel.topAnchor.constraint(equalTo: dividerLabel.bottomAnchor).isActive = true
carbLabel.font = UIFont(name: "Verdana", size: 14)
proteinLabel.translatesAutoresizingMaskIntoConstraints = false
proteinLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
proteinLabel.topAnchor.constraint(equalTo: carbLabel.bottomAnchor).isActive = true
proteinLabel.font = UIFont(name: "Verdana", size: 14)
fatLabel.translatesAutoresizingMaskIntoConstraints = false
fatLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
fatLabel.topAnchor.constraint(equalTo: proteinLabel.bottomAnchor).isActive = true
fatLabel.font = UIFont(name: "Verdana", size: 14)
sugarLabel.translatesAutoresizingMaskIntoConstraints = false
sugarLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
sugarLabel.topAnchor.constraint(equalTo: fatLabel.bottomAnchor).isActive = true
sugarLabel.font = UIFont(name: "Verdana", size: 14)
sugarWarningLabel.translatesAutoresizingMaskIntoConstraints = false
sugarWarningLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
sugarWarningLabel.topAnchor.constraint(equalTo: sugarLabel.bottomAnchor).isActive = true
sugarWarningLabel.font = UIFont(name: "Verdana-Bold", size: 14)
}
func setupdata(){
if let fruit = fruit{
nameLabel.text = fruit.name
genusLabel.text = "Genus : \(fruit.genus)"
familyLabel.text = "Family : \(fruit.family)"
orderLabel.text = "Order : \(fruit.order)"
dividerLabel.text = "Nutritional value"
let id = fruit.id
let idString = String(id)
idLabel.text = "ID : \(idString)"
let carbs = fruit.nutritions.carbohydrates
let carbString = String(carbs)
carbLabel.text = "Carbohydrates : \(carbString)"
let protein = fruit.nutritions.protein
let proteinString = String(protein)
proteinLabel.text = "Proteins : \(proteinString)"
let fat = fruit.nutritions.fat
let fatString = String(fat)
fatLabel.text = "Fat : \(fatString)"
let calories = fruit.nutritions.calories
let calorieString = String(calories)
caloriesLabel.text = "Carbohydrates : \(calorieString)"
let sugar = fruit.nutritions.sugar
let sugarString = String(sugar)
sugarLabel.text = "Sugar : \(sugarString)"
}
}
func setupDismissButton(){
view.addSubview(dismissButton)
dismissButton.translatesAutoresizingMaskIntoConstraints = false
dismissButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
dismissButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
dismissButton.setTitle("Tilbake",for: .normal)
dismissButton.setTitleColor(UIColor.black, for: .normal)
dismissButton.addTarget(self, action: #selector(dismissAction), for: .touchUpInside)
}
#objc func dismissAction(){
self.dismiss(animated: true)
}
}
The "presentation layer" of your animation is probably covering your dismiss button and preventing it from being tapped. Try adding a print statement to your dismissAction() and see if it gets called when you tap the button on a screen with the animating background.
That's a guess, but a pretty good guess.
To fix the problem, try adding a view to your view's content view, under all the other views (button, labels, etc.) Let's call that new view your colorView. Change your animation to animate the background color of the colorView instead of animating the color of the view controller's content view. I'm not certain that will fix it, but it's worth a try.
When its clicked on some cell, DetailViewController will be opened. Problem is that context from DetailViewController is shown while transitioning between controllers.
Picture below presents problem:
image
DetailViewController is called in function:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let singleMovie = movieList[indexPath.row]
getSingleMovie(movieId: singleMovie.id, completion: {})
getDirector(movieId: singleMovie.id, completion: { [weak self] in
guard let self = self else { return }
var directorName = ""
self.creditResponse?.crew.forEach({ singleCredit in
if singleCredit.knownForDepartment == .directing {
directorName = singleCredit.name
}
})
guard let safeMovie = self.detailMovie else {return}
let detailVc = DetailViewController(movie: safeMovie, groups: self.checkGroups(groups: singleMovie.genreIds), director: directorName, movieIndex: indexPath.row)
self.navigationController?.pushViewController(detailVc, animated: true)
})
}
DetailViewController:
import UIKit
class DetailViewController: UIViewController {
let movie: Details?
let groupsValue: String?
let directorValue: String?
let movieIndex: Int?
var checkButton: Bool = false
var favoriteButton: Bool = false
let backButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "Icon"), for: .normal)
button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
return button
}()
var movieTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Quicksand-Bold", size: 40)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
var groupsLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Quicksand-Regular", size: 20)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var directorLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Quicksand-Bold", size: 20)
label.textColor = .white
label.text = "Director: "
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var directorNameLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Quicksand-Regular", size: 20)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var descriptionLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "Quicksand-Regular", size: 20)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
var movieImageView: UIImageView = {
let iv = UIImageView()
iv.layer.cornerRadius = 15
iv.layer.masksToBounds = true
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
let buttonChecked: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.tintColor = UIColor(red: 0.475, green: 0.729, blue: 0.757, alpha: 1)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 35, left: 35, bottom: 35, right: 35)
button.tintColor = UIColor(red: 0.475, green: 0.729, blue: 0.757, alpha: 1)
button.addTarget(self, action: #selector(checkButtonTapped), for: .touchUpInside)
return button
}()
let buttonFavorite: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.tintColor = UIColor(red: 0.475, green: 0.729, blue: 0.757, alpha: 1)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 35, left: 35, bottom: 35, right: 35)
button.tintColor = UIColor(red: 0.475, green: 0.729, blue: 0.757, alpha: 1)
button.addTarget(self, action: #selector(favoriteButtonTapped), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationItem.hidesBackButton = true
setupUI()
}
init(movie:Details, groups: String, director: String, movieIndex: Int) {
self.movie = movie
self.groupsValue = groups
self.directorValue = director
self.movieIndex = movieIndex
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DetailViewController{
#objc func backButtonTapped() {
navigationController?.popToRootViewController(animated: true)
}
}
extension DetailViewController {
func setupUI(){
view.addSubview(movieTitleLabel)
view.addSubview(groupsLabel)
view.addSubview(directorLabel)
view.addSubview(descriptionLabel)
view.addSubview(directorNameLabel)
view.addSubview(movieImageView)
view.addSubview(backButton)
view.addSubview(buttonChecked)
view.addSubview(buttonFavorite)
setupValues()
setupConstraints()
setupButtons()
}
}
extension DetailViewController {
func setupConstraints(){
let bottomImageConstraint = movieImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
bottomImageConstraint.priority = .defaultLow
NSLayoutConstraint.activate([
movieImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
movieImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
movieImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomImageConstraint,
movieImageView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3),
movieTitleLabel.topAnchor.constraint(equalTo: movieImageView.bottomAnchor, constant: 10),
movieTitleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
movieTitleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
groupsLabel.topAnchor.constraint(equalTo: movieTitleLabel.bottomAnchor, constant: 10),
groupsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
directorLabel.topAnchor.constraint(equalTo: groupsLabel.bottomAnchor, constant: 10),
directorLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
directorLabel.topAnchor.constraint(equalTo: groupsLabel.bottomAnchor, constant: 10),
directorLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
directorNameLabel.topAnchor.constraint(equalTo: groupsLabel.bottomAnchor, constant: 10),
directorNameLabel.leadingAnchor.constraint(equalTo: directorLabel.trailingAnchor, constant: 10),
descriptionLabel.topAnchor.constraint(equalTo: directorLabel.bottomAnchor, constant: 10),
descriptionLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
descriptionLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
backButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
backButton.heightAnchor.constraint(equalToConstant: 40),
backButton.widthAnchor.constraint(equalToConstant: 40),
buttonFavorite.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
buttonFavorite.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
buttonChecked.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
buttonChecked.trailingAnchor.constraint(equalTo: buttonFavorite.trailingAnchor, constant: -50),
])
}
func setupValues(){
movieTitleLabel.text = movie?.title
guard let safeUrl = movie?.posterPath else {return}
movieImageView.downloadImage(from: safeUrl)
descriptionLabel.text = movie?.overview
groupsLabel.text = groupsValue
directorNameLabel.text = directorValue
}
func setupButtons(){
let checkValue = UserDefaults.standard.bool(forKey: "checkButton\(movieIndex ?? 0)")
let favoriteValue = UserDefaults.standard.bool(forKey: "favoriteButton\(movieIndex ?? 0)")
if checkValue == true {
buttonChecked.setImage(UIImage(systemName: "checkmark.seal.fill"), for: .normal)
}
else {
buttonChecked.setImage(UIImage(systemName: "checkmark.seal"), for: .normal)
}
if favoriteValue == true {
buttonFavorite.setImage(UIImage(systemName: "star.fill"), for: .normal)
}
else {
buttonFavorite.setImage(UIImage(systemName: "star"), for: .normal)
}
}
}
extension DetailViewController{
#objc func checkButtonTapped() {
checkButton = !checkButton
if checkButton == true {
DispatchQueue.main.async {
self.buttonChecked.setImage(UIImage(systemName: "checkmark.seal.fill"), for: .normal)
}
}
else {
DispatchQueue.main.async {
self.buttonChecked.setImage(UIImage(systemName: "checkmark.seal"), for: .normal)
}
}
UserDefaults.standard.set(checkButton, forKey: "checkButton\(movieIndex ?? 0)")
}
#objc func favoriteButtonTapped() {
favoriteButton = !favoriteButton
if favoriteButton == true {
DispatchQueue.main.async {
self.buttonFavorite.setImage(UIImage(systemName: "star.fill"), for: .normal)
}
}
else {
DispatchQueue.main.async {
self.buttonFavorite.setImage(UIImage(systemName: "star"), for: .normal)
}
}
UserDefaults.standard.set(favoriteButton, forKey: "favoriteButton\(movieIndex ?? 0)")
}
}
How to setup animations so it transits normally?
Transition GIF
It looks like your DetailViewController.view has no backgroundColor set (OR it is .clear).
Please assign a backgroundColor to your view like this.
override func viewDidLoad() {
super.viewDidLoad()
// For testing, you may want to set this to something else like `.red` / `.yellow`
// This will help you in identifying where the issue is
self.view.backgroundColor = .black
}
Here is the screenshot if the errorI am building the ui of the app programatically and when i run the app it runs perfectly but when i turn the simulation in landscape mode the console shows some layouts errors. Is it okay to just tick the orientation to portrait only in the general app settings because my app is running perfectly in portrait mode and i don't want to run the app in any other orientations or am i making some problems in constraints? Here is my code for the ui...
`let top = UIColor(red: 217/255, green: 30/255, blue: 133/255, alpha: 1)
let bottom = UIColor(red: 242/255, green: 56/255, blue: 15/255, alpha: 1)
let colorOne = UIColor(red: 38/255, green: 38/255, blue: 38/255, alpha: 1)
let colorTwo = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1)
let colorTop = UIColor.red
let colorBottom = UIColor.green
let topContainer: UIView = {
let top = UIView()
top.translatesAutoresizingMaskIntoConstraints = false
top.backgroundColor = .black
return top
}()
let model: UIImageView = {
let mymodel = UIImageView(image: #imageLiteral(resourceName: "bodybuilder"))
mymodel.translatesAutoresizingMaskIntoConstraints = false
mymodel.contentMode = .scaleToFill
return mymodel
}()
let logo: UIImageView = {
let gymble = UIImageView(image: #imageLiteral(resourceName: "Gymble"))
gymble.contentMode = .scaleAspectFill
gymble.translatesAutoresizingMaskIntoConstraints = false
return gymble
}()
let bottomContainer: UIView = {
let bottom = UIView()
bottom.translatesAutoresizingMaskIntoConstraints = false
return bottom
}()
let pinField: UITextField = {
let phone = UITextField()
phone.backgroundColor = .white
phone.text = "+91"
phone.textAlignment = .center
phone.layer.cornerRadius = 5
phone.font = UIFont(name: "Roboto-Regular", size: 20)
phone.keyboardType = UIKeyboardType.numberPad
phone.translatesAutoresizingMaskIntoConstraints = false
return phone
}()
let phoneFeild: UITextField = {
let phone = UITextField()
phone.backgroundColor = .white
phone.placeholder = "Phone number"
phone.layer.cornerRadius = 5
phone.font = UIFont(name: "Roboto-Regular", size: 20)
phone.keyboardType = UIKeyboardType.phonePad
phone.keyboardAppearance = UIKeyboardAppearance.dark
phone.translatesAutoresizingMaskIntoConstraints = false
return phone
}()
let loginButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Login", for: .normal)
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
button.titleLabel?.font = UIFont(name: "Roboto-Medium", size: 22)
button.addTarget(self, action: #selector(someButtonAction), for: .touchUpInside)
return button
}()
let laterButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("I'll login later", for: .normal)
button.setTitleColor(.gray, for: .normal)
button.titleLabel?.font = UIFont(name: "Roboto-Light", size: 16)
return button
}()
let horizontalStack: UIStackView = {
let mystack = UIStackView()
mystack.alignment = UIStackView.Alignment.center
mystack.axis = NSLayoutConstraint.Axis.horizontal
mystack.translatesAutoresizingMaskIntoConstraints = false
mystack.distribution = .fill
mystack.spacing = 15
return mystack
}()
let stack: UIStackView = {
let mystack = UIStackView()
mystack.alignment = UIStackView.Alignment.center
mystack.axis = NSLayoutConstraint.Axis.vertical
mystack.translatesAutoresizingMaskIntoConstraints = false
mystack.distribution = .equalSpacing
return mystack
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
view.addSubview(topContainer)
topContainerLayout()
topContainer.addSubview(model)
modelLayout()
view.addSubview(bottomContainer)
bottomContainerLayout()
bottomContainer.addSubview(stack)
stackLayout()
stack.addArrangedSubview(logo)
logoLayout()
stack.addArrangedSubview(horizontalStack)
horizontalStackLayout()
horizontalStack.addArrangedSubview(pinField)
pinFieldLayout()
let padding = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: self.phoneFeild.frame.height))
phoneFeild.leftView = padding
phoneFeild.leftViewMode = UITextField.ViewMode.always
horizontalStack.addArrangedSubview(phoneFeild)
phoneFieldLayout()
let gradientWidth = (UIScreen.main.bounds.width - 32)
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [top.cgColor, bottom.cgColor]
gradientLayer.locations = [0.15, 1]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
gradientLayer.frame = CGRect(x: 0, y: 0, width: gradientWidth, height: 50)
gradientLayer.cornerRadius = 5
loginButton.layer.insertSublayer(gradientLayer, at: 0)
stack.addArrangedSubview(loginButton)
loginButtonLayout()
stack.addArrangedSubview(laterButton)
LaterButtonLayout()
}
func LaterButtonLayout(){
laterButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
func loginButtonLayout(){
loginButton.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -32).isActive = true
loginButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
}
func logoLayout(){
logo.topAnchor.constraint(equalTo: stack.topAnchor).isActive = true
logo.heightAnchor.constraint(equalToConstant: 56).isActive = true
logo.widthAnchor.constraint(equalToConstant: 60).isActive = true
}
func stackLayout(){
stack.heightAnchor.constraint(equalTo: bottomContainer.heightAnchor).isActive = true
stack.widthAnchor.constraint(equalTo: bottomContainer.widthAnchor).isActive = true
}
func horizontalStackLayout(){
horizontalStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
horizontalStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
horizontalStack.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
func pinFieldLayout(){
pinField.leadingAnchor.constraint(equalTo: horizontalStack.leadingAnchor).isActive = true
pinField.topAnchor.constraint(equalTo: horizontalStack.topAnchor).isActive = true
pinField.bottomAnchor.constraint(equalTo: horizontalStack.bottomAnchor).isActive = true
pinField.widthAnchor.constraint(equalToConstant: 50).isActive = true
}
func phoneFieldLayout(){
phoneFeild.leadingAnchor.constraint(equalTo: pinField.trailingAnchor, constant: 15).isActive = true
phoneFeild.topAnchor.constraint(equalTo: horizontalStack.topAnchor).isActive = true
phoneFeild.bottomAnchor.constraint(equalTo: horizontalStack.bottomAnchor).isActive = true
}
func modelLayout(){
model.topAnchor.constraint(equalTo: topContainer.topAnchor).isActive = true
model.leadingAnchor.constraint(equalTo: topContainer.leadingAnchor).isActive = true
model.trailingAnchor.constraint(equalTo: topContainer.trailingAnchor).isActive = true
model.heightAnchor.constraint(equalTo: topContainer.heightAnchor).isActive = true
}
func bottomContainerLayout(){
bottomContainer.topAnchor.constraint(equalTo: topContainer.bottomAnchor).isActive = true
bottomContainer.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
bottomContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
bottomContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
func topContainerLayout(){
topContainer.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
topContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 2/3 , constant: -20).isActive = true
topContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
topContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
#objc func someButtonAction(){
print("Button is tapped!")
let opt = OTPViewController()
present(opt, animated: true, completion: nil)
}
}
`
If you want to customize app orientation do this:
Go to General setting of project
in Deployment , change device orientation .
Probably you didn't make auto layout.
Please check this out -> Auto Layout Guide
And this -> Programmatically Creating Constraints
Edit:
Use that translatesAutoresizingMaskIntoConstraints = false after addSubView.For example
func topContainerLayout(){
topContainer.translatesAutoresizingMaskIntoConstraints = false
topContainer.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
topContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 2/3 , constant: -20).isActive = true
topContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
topContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
So I'm trying to add two buttons of equal width to my view next to each other. I have used a stack view as I thought this would work better.
The second button named "Sort" is only one visible at the correct width but covers over my "Add" button leaving and empty space next to it.
I have run it without the "Sort" button and I just get the "Add" button showing across the whole stack view as I would expect so bit confused but this.
Code is below not sure what's going on with it. If think its better to not use stackView need just a little bit of advice on best way to work the constraints. Thanks everyone.
And just to say I'm working only in programmatic with this.
import UIKit
class PlacesVC: UIViewController {
let topTitle = UILabel()
let logoImage = UIImage(named: "DIYCoffeeLogoDark")
let logoImageView = UIImageView()
let addButton = UIButton()
let sortButton = UIButton()
let buttonStack = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = #colorLiteral(red: 0.9324248433, green: 0.9268818498, blue: 0.9366856217, alpha: 1)
logoImageView.image = logoImage
self.navigationItem.titleView = logoImageView
self.navigationController?.navigationBar.isHidden = false
view.addSubview(topTitle)
view.addSubview(buttonStack)
setUpTopTital()
setUpButtonStack()
}
func setUpTopTital() {
topTitle.translatesAutoresizingMaskIntoConstraints = false
topTitle.font = UIFont(name: "Futura", size: 25)
topTitle.text = "Your Saved Places"
topTitle.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
topTitle.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
topTitle.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
topTitle.heightAnchor.constraint(equalToConstant: 30).isActive = true
}
func setUpButtonStack() {
buttonStack.translatesAutoresizingMaskIntoConstraints = false
buttonStack.addArrangedSubview(addButton)
buttonStack.addArrangedSubview(sortButton)
buttonStack.distribution = .fillProportionally
buttonStack.alignment = .center
buttonStack.axis = .horizontal
buttonStack.spacing = 20
buttonStack.topAnchor.constraint(equalTo: topTitle.bottomAnchor, constant: 20).isActive = true
buttonStack.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
buttonStack.widthAnchor.constraint(equalToConstant: view.frame.width - 40).isActive = true
buttonStack.heightAnchor.constraint(equalToConstant: 30).isActive = true
setUpAddButton()
setUpSortButton()
}
func setUpAddButton() {
addButton.translatesAutoresizingMaskIntoConstraints = false
addButton.titleLabel?.font = UIFont(name: "Futura", size: 20)
addButton.setTitle("ADD", for: .normal)
addButton.backgroundColor = #colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1)
addButton.layer.cornerRadius = 5
addButton.setTitleColor(.white, for: .normal)
}
func setUpSortButton() {
addButton.translatesAutoresizingMaskIntoConstraints = false
addButton.titleLabel?.font = UIFont(name: "Futura", size: 20)
addButton.setTitle("SORT", for: .normal)
addButton.backgroundColor = #colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1)
addButton.layer.cornerRadius = 5
addButton.setTitleColor(.white, for: .normal)
}
In both functions, setUpAddButton() and setUpSortButton() you are using same button that is addButton.
Change addButton to sortButton inside setUpSortButton(), then you are able to see both buttons in your stackview.
func setUpSortButton() {
sortButton.translatesAutoresizingMaskIntoConstraints = false
sortButton.titleLabel?.font = UIFont(name: "Futura", size: 20)
sortButton.setTitle("SORT", for: .normal)
sortButton.backgroundColor = #colorLiteral(red: 0.3176470697, green: 0.07450980693, blue: 0.02745098062, alpha: 1)
sortButton.layer.cornerRadius = 5
sortButton.setTitleColor(.white, for: .normal)
}
I'm trying to make the same behavior of the Material design textfield with a custom textfield.
I created a class that inherits from textfield and every thing is working fine. The only problem is in one scenario. when I have an object under the textfield, and i add the error label under the text field. the error label might be more than one line. so it overlays the object under the textfield. However, in the material design library, the objects under the textfield are automatically pushed down according ton the number of lines of the error label.
here is my custom textfield code:
import UIKit
import RxSwift
import RxCocoa
class FloatingTextField2: UITextField {
var placeholderLabel: UILabel!
var line: UIView!
var errorLabel: UILabel!
let bag = DisposeBag()
var activeColor = Constants.colorBlue
var inActiveColor = UIColor(red: 84/255.0, green: 110/255.0, blue: 122/255.0, alpha: 0.8)
var errorColorFull = UIColor(red: 254/255.0, green: 103/255.0, blue: 103/255.0, alpha: 1.0)
//var errorColorParcial = UIColor(red: 254/255.0, green: 103/255.0, blue: 103/255.0, alpha: 0.5)
private var lineYPosition: CGFloat!
private var lineXPosition: CGFloat!
private var lineWidth: CGFloat!
private var lineHeight: CGFloat!
private var errorLabelYPosition: CGFloat!
private var errorLabelXPosition: CGFloat!
private var errorLabelWidth: CGFloat!
private var errorLabelHeight: CGFloat!
var maxFontSize: CGFloat = 14
var minFontSize: CGFloat = 11
let errorLabelFont = UIFont(name: "Lato-Regular", size: 12)
var animationDuration = 0.35
var placeholderText: String = "" {
didSet {
if placeholderLabel != nil {
placeholderLabel.text = placeholderText
}
}
}
var isTextEntrySecured: Bool = false {
didSet {
self.isSecureTextEntry = isTextEntrySecured
}
}
override func draw(_ rect: CGRect) {
//setUpUI()
}
override func awakeFromNib() {
setUpUI()
}
func setUpUI() {
if placeholderLabel == nil {
placeholderLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: 20))
self.addSubview(placeholderLabel)
self.borderStyle = .none
placeholderLabel.text = "Placeholder Preview"
placeholderLabel.textColor = inActiveColor
self.font = UIFont(name: "Lato-Regular", size: maxFontSize)
self.placeholderLabel.font = UIFont(name: "Lato-Regular", size: maxFontSize)
self.placeholder = ""
self.textColor = .black
setUpTextField()
}
if line == nil {
lineYPosition = self.frame.height
lineXPosition = -16
lineWidth = self.frame.width + 32
lineHeight = 1
line = UIView(frame: CGRect(x: lineXPosition, y: lineYPosition, width: lineWidth, height: lineHeight))
self.addSubview(line)
line.backgroundColor = inActiveColor
}
if errorLabel == nil {
errorLabelYPosition = lineYPosition + 8
errorLabelXPosition = 0
errorLabelWidth = self.frame.width
errorLabelHeight = calculateErrorLabelHeight(text: "")
errorLabel = UILabel(frame: CGRect(x: 0, y: errorLabelYPosition, width: errorLabelWidth, height: errorLabelHeight))
self.addSubview(errorLabel)
errorLabel.numberOfLines = 0
errorLabel.textColor = errorColorFull
errorLabel.text = ""
errorLabel.font = errorLabelFont
sizeToFit()
}
}
func setUpTextField(){
self.rx.controlEvent(.editingDidBegin).subscribe(onNext: { (next) in
if self.text?.isEmpty ?? false {
self.animatePlaceholderUp()
}
}).disposed(by: bag)
self.rx.controlEvent(.editingDidEnd).subscribe(onNext: { (next) in
if self.text?.isEmpty ?? false {
self.animatePlaceholderCenter()
}
}).disposed(by: bag)
}
func setErrorText(_ error: String?, errorAccessibilityValue: String?) {
if let errorText = error {
self.resignFirstResponder()
errorLabelHeight = calculateErrorLabelHeight(text: errorText)
self.errorLabel.frame = CGRect(x: 0, y: errorLabelYPosition, width: errorLabelWidth, height: errorLabelHeight)
self.errorLabel.text = errorText
self.errorLabel.isHidden = false
self.line.backgroundColor = errorColorFull
}else{
self.errorLabel.text = ""
self.errorLabel.isHidden = true
}
errorLabel.accessibilityIdentifier = errorAccessibilityValue ?? "textinput_error"
}
func animatePlaceholderUp(){
UIView.animate(withDuration: animationDuration, animations: {
self.line.frame.size.height = 2
self.line.backgroundColor = self.activeColor
self.placeholderLabel.font = self.placeholderLabel.font.withSize(self.minFontSize)
self.placeholderLabel.textColor = self.activeColor
self.placeholderLabel.frame = CGRect(x: 0, y: (self.frame.height/2 + 8) * -1, width: self.frame.width, height: self.frame.height)
self.layoutIfNeeded()
}) { (done) in
}
}
func animatePlaceholderCenter(){
UIView.animate(withDuration: animationDuration, animations: {
self.line.frame.size.height = 1
self.line.backgroundColor = self.inActiveColor
self.placeholderLabel.font = self.placeholderLabel.font.withSize(self.maxFontSize)
self.placeholderLabel.textColor = self.inActiveColor
self.placeholderLabel.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
self.layoutIfNeeded()
}) { (done) in
}
}
func calculateErrorLabelHeight(text:String) -> CGFloat{
let font = errorLabelFont
let width = self.frame.width
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
How can I solve this problem? I could not find anything on stack overflow or google related to my problem.
As mentioned in the comments:
You'll be much better off using constraints rather than explicit frames
Adding subviews to a UITextField will show them outside the Bounds of the field, meaning they won't affect the frame (and thus the constraints)
If the constraints are set properly, they will control the "containing view" height
The key to getting your "error" label to expand the view is to apply multiple vertical constraints, and activate / deactivate as needed.
Here is a complete example of a custom UIView which contains a text field, a placeholder label and an error label. The example view controller includes "demo" buttons to show the capabilities.
I suggest you add this code and try it out. If it suits your needs, there are plenty of comments in it that you should be able to tweak fonts, spacing, etc to your liking.
Or, it should at least give you some ideas of how to set up your own.
FloatingTextFieldView - UIView subclass
class FloatingTextFieldView: UIView, UITextFieldDelegate {
var placeHolderTopConstraint: NSLayoutConstraint!
var placeHolderCenterYConstraint: NSLayoutConstraint!
var placeHolderLeadingConstraint: NSLayoutConstraint!
var lineHeightConstraint: NSLayoutConstraint!
var errorLabelBottomConstraint: NSLayoutConstraint!
var activeColor: UIColor = UIColor.blue
var inActiveColor: UIColor = UIColor(red: 84/255.0, green: 110/255.0, blue: 122/255.0, alpha: 0.8)
var errorColorFull: UIColor = UIColor(red: 254/255.0, green: 103/255.0, blue: 103/255.0, alpha: 1.0)
var animationDuration = 0.35
var maxFontSize: CGFloat = 14
var minFontSize: CGFloat = 11
let errorLabelFont = UIFont(name: "Lato-Regular", size: 12)
let placeholderLabel: UILabel = {
let v = UILabel()
v.text = "Default Placeholder"
v.setContentHuggingPriority(.required, for: .vertical)
return v
}()
let line: UIView = {
let v = UIView()
v.backgroundColor = .lightGray
return v
}()
let errorLabel: UILabel = {
let v = UILabel()
v.numberOfLines = 0
v.text = "Default Error"
v.setContentCompressionResistancePriority(.required, for: .vertical)
return v
}()
let textField: UITextField = {
let v = UITextField()
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
clipsToBounds = true
backgroundColor = .white
[textField, line, placeholderLabel, errorLabel].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
addSubview($0)
}
// place holder label gets 2 vertical constraints
// top of view
// centerY to text field
placeHolderTopConstraint = placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
placeHolderCenterYConstraint = placeholderLabel.centerYAnchor.constraint(equalTo: textField.centerYAnchor, constant: 0.0)
// place holder leading constraint is 16-pts (when centered on text field)
// when animated above text field, we'll change the constant to 0
placeHolderLeadingConstraint = placeholderLabel.leadingAnchor.constraint(equalTo: textField.leadingAnchor, constant: 16.0)
// error label bottom constrained to bottom of view
// will be activated when shown, deactivated when hidden
errorLabelBottomConstraint = errorLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
// line height constraint constant changes between 1 and 2 (inactive / active)
lineHeightConstraint = line.heightAnchor.constraint(equalToConstant: 1.0)
NSLayoutConstraint.activate([
// text field top 16-pts from top of view
// leading and trailing = 0
textField.topAnchor.constraint(equalTo: topAnchor, constant: 16.0),
textField.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0),
textField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0),
// text field height = 24
textField.heightAnchor.constraint(equalToConstant: 24.0),
// text field bottom is AT LEAST 4 pts
textField.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -4.0),
// line view top is 2-pts below text field bottom
// leading and trailing = 0
line.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 2.0),
line.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0),
line.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0),
// error label top is 4-pts from text field bottom
// leading and trailing = 0
errorLabel.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 4.0),
errorLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0),
errorLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0),
placeHolderCenterYConstraint,
placeHolderLeadingConstraint,
lineHeightConstraint,
])
// I'm not using Rx, so set the delegate
textField.delegate = self
textField.font = UIFont(name: "Lato-Regular", size: maxFontSize)
textField.textColor = .black
placeholderLabel.font = UIFont(name: "Lato-Regular", size: maxFontSize)
placeholderLabel.textColor = inActiveColor
line.backgroundColor = inActiveColor
errorLabel.textColor = errorColorFull
errorLabel.font = errorLabelFont
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text?.isEmpty ?? false {
self.animatePlaceholderUp()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text?.isEmpty ?? false {
self.animatePlaceholderCenter()
}
}
func animatePlaceholderUp() -> Void {
UIView.animate(withDuration: animationDuration, animations: {
// increase line height
self.lineHeightConstraint.constant = 2.0
// set line to activeColor
self.line.backgroundColor = self.activeColor
// set placeholder label font and color
self.placeholderLabel.font = self.placeholderLabel.font.withSize(self.minFontSize)
self.placeholderLabel.textColor = self.activeColor
// deactivate placeholder label CenterY constraint
self.placeHolderCenterYConstraint.isActive = false
// activate placeholder label Top constraint
self.placeHolderTopConstraint.isActive = true
// move placeholder label leading to 0
self.placeHolderLeadingConstraint.constant = 0
self.layoutIfNeeded()
}) { (done) in
}
}
func animatePlaceholderCenter() -> Void {
UIView.animate(withDuration: animationDuration, animations: {
// decrease line height
self.lineHeightConstraint.constant = 1.0
// set line to inactiveColor
self.line.backgroundColor = self.inActiveColor
// set placeholder label font and color
self.placeholderLabel.font = self.placeholderLabel.font.withSize(self.maxFontSize)
self.placeholderLabel.textColor = self.inActiveColor
// deactivate placeholder label Top constraint
self.placeHolderTopConstraint.isActive = false
// activate placeholder label CenterY constraint
self.placeHolderCenterYConstraint.isActive = true
// move placeholder label leading to 16
self.placeHolderLeadingConstraint.constant = 16
self.layoutIfNeeded()
}) { (done) in
}
}
func setErrorText(_ error: String?, errorAccessibilityValue: String?, endEditing: Bool) {
if let errorText = error {
UIView.animate(withDuration: 0.05, animations: {
self.errorLabel.text = errorText
self.line.backgroundColor = self.errorColorFull
self.errorLabel.isHidden = false
// activate error label Bottom constraint
self.errorLabelBottomConstraint.isActive = true
}) { (done) in
if endEditing {
self.textField.resignFirstResponder()
}
}
}else{
UIView.animate(withDuration: 0.05, animations: {
self.errorLabel.text = ""
self.line.backgroundColor = self.inActiveColor
self.errorLabel.isHidden = true
// deactivate error label Bottom constraint
self.errorLabelBottomConstraint.isActive = false
}) { (done) in
if endEditing {
self.textField.resignFirstResponder()
}
}
}
errorLabel.accessibilityIdentifier = errorAccessibilityValue ?? "textinput_error"
}
// func to set / clear element background colors
// to make it easy to see the frames
func showHideFrames(show b: Bool) -> Void {
if b {
self.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 1.0, alpha: 1.0)
placeholderLabel.backgroundColor = .cyan
errorLabel.backgroundColor = .green
textField.backgroundColor = .yellow
} else {
self.backgroundColor = .white
[placeholderLabel, errorLabel, textField].forEach {
$0.backgroundColor = .clear
}
}
}
}
DemoFLoatingTextViewController
class DemoFLoatingTextViewController: UIViewController {
// FloatingTextFieldView
let sampleFTF: FloatingTextFieldView = {
let v = FloatingTextFieldView()
return v
}()
// a label to constrain below the FloatingTextFieldView
// so we can see it gets "pushed down"
let demoLabel: UILabel = {
let v = UILabel()
v.numberOfLines = 0
v.text = "This is a label outside the Floating Text Field. As you will see, it gets \"pushed down\" when the error label is shown."
v.backgroundColor = .brown
v.textColor = .yellow
return v
}()
// buttons to Demo the functionality
let btnA: UIButton = {
let b = UIButton(type: .system)
b.setTitle("End Editing", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnB: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Set Error", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnC: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Clear Error", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnD: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Set & End", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnE: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Clear & End", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnF: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Show Frames", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let btnG: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Hide Frames", for: .normal)
b.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
return b
}()
let errorMessages: [String] = [
"Simple Error",
"This will end up being a Multiline Error message. It is long enough to cause word wrapping."
]
var errorCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// add Demo buttons
let btnStack = UIStackView()
btnStack.axis = .vertical
btnStack.spacing = 6
btnStack.translatesAutoresizingMaskIntoConstraints = false
[[btnA], [btnB, btnC], [btnD, btnE], [btnF, btnG]].forEach { btns in
let sv = UIStackView()
sv.distribution = .fillEqually
sv.spacing = 12
sv.translatesAutoresizingMaskIntoConstraints = false
btns.forEach {
sv.addArrangedSubview($0)
}
btnStack.addArrangedSubview(sv)
}
view.addSubview(btnStack)
// add FloatingTextFieldView and demo label
view.addSubview(sampleFTF)
view.addSubview(demoLabel)
sampleFTF.translatesAutoresizingMaskIntoConstraints = false
demoLabel.translatesAutoresizingMaskIntoConstraints = false
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// buttons stack Top = 20, centerX, width = 80% of view width
btnStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
btnStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
btnStack.widthAnchor.constraint(equalTo: g.widthAnchor, multiplier: 0.8),
// FloatingTextFieldView Top = 40-pts below buttons stack
sampleFTF.topAnchor.constraint(equalTo: btnStack.bottomAnchor, constant: 40.0),
// FloatingTextFieldView Leading = 60-pts
sampleFTF.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 60.0),
// FloatingTextFieldView width = 240
sampleFTF.widthAnchor.constraint(equalToConstant: 240.0),
// Note: we are not setting the FloatingTextFieldView Height!
// constrain demo label Top = 8-pts below FloatingTextFieldView bottom
demoLabel.topAnchor.constraint(equalTo: sampleFTF.bottomAnchor, constant: 8.0),
// Leading = FloatingTextFieldView Leading
demoLabel.leadingAnchor.constraint(equalTo: sampleFTF.leadingAnchor),
// Width = 200
demoLabel.widthAnchor.constraint(equalToConstant: 200.0),
])
// add touchUpInside targets for demo buttons
btnA.addTarget(self, action: #selector(endEditing(_:)), for: .touchUpInside)
btnB.addTarget(self, action: #selector(setError(_:)), for: .touchUpInside)
btnC.addTarget(self, action: #selector(clearError(_:)), for: .touchUpInside)
btnD.addTarget(self, action: #selector(setAndEnd(_:)), for: .touchUpInside)
btnE.addTarget(self, action: #selector(clearAndEnd(_:)), for: .touchUpInside)
btnF.addTarget(self, action: #selector(showFrames(_:)), for: .touchUpInside)
btnG.addTarget(self, action: #selector(hideFrames(_:)), for: .touchUpInside)
}
#objc func endEditing(_ sender: Any) -> Void {
sampleFTF.textField.resignFirstResponder()
}
#objc func setError(_ sender: Any) -> Void {
sampleFTF.setErrorText(errorMessages[errorCount % 2], errorAccessibilityValue: "", endEditing: false)
errorCount += 1
}
#objc func clearError(_ sender: Any) -> Void {
sampleFTF.setErrorText(nil, errorAccessibilityValue: "", endEditing: false)
}
#objc func setAndEnd(_ sender: Any) -> Void {
sampleFTF.setErrorText(errorMessages[errorCount % 2], errorAccessibilityValue: "", endEditing: true)
errorCount += 1
}
#objc func clearAndEnd(_ sender: Any) -> Void {
sampleFTF.setErrorText(nil, errorAccessibilityValue: "", endEditing: true)
}
#objc func showFrames(_ sender: Any) -> Void {
sampleFTF.showHideFrames(show: true)
}
#objc func hideFrames(_ sender: Any) -> Void {
sampleFTF.showHideFrames(show: false)
}
}
Example results: