storyboard.instantiateViewController executes for about 3 seconds - ios

I noticed that my app has a delay before presenting UIViewController, so I used print() to find out which line of code causing it and found up that let navigationVC = storyboard!.instantiateViewController(withIdentifier: "filterNavigationVC") as! UINavigationController executes for about 2 seconds. Why might it be like that? I've tried to remove everything except this one without even navigating and still it took that long.
#IBAction func filter(_ sender: AnyObject) {
let navigationVC = storyboard!.instantiateViewController(withIdentifier: "filterNavigationVC") as! UINavigationController
let destinationVC = navigationVC.topViewController as! FilterViewController
navigationVC.modalPresentationStyle = .overCurrentContext
destinationVC.backgroundColorValue = self.view.backgroundColor!
destinationVC.color = themeColor.light
destinationVC.delegate = self
destinationVC.billModel = self.price
destinationVC.applyedFilter = self.applyedFilter
self.present(navigationVC, animated: true, completion: nil)
}
Next UIViewController's viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
customization()
}
fileprivate func customization(){
setupBillButtons(billModel.range["low"]!, medium: self.billModel.range["medium"]!, high: self.billModel.range["high"]!)
tempConfigButtons([self.lowBillButton, self.mediumBillButton, self.highBillButton])
if color == themeColor.light {
customizeLightTheme()
} else if color == themeColor.dark {
customizeDarkTheme()
}
setCharacterSpacingForLabels([typeLabel, kitchenLabel, avarageBill, metroLabel, tagsLabel], spacing: 2.79)
setSeparatorInsets([kitchenTableView, metroTableView, typeTableView], edge: UIEdgeInsetsMake(0, 20, 0, 20))
backgroundVoew.backgroundColor = backgroundColorValue
backgroundVoew.addBackroundBlur()
self.navigationController?.navigationBar.isHidden = true
}
fileprivate func customizeDarkTheme() {
comfirmButton.setImage(UIImage(named: "comfirmLight"), for: UIControlState())
dismissButton.setImage(UIImage(named: "closeLight"), for: UIControlState())
setColorsForTableViews([kitchenTableView, metroTableView, typeTableView], separatorColor: colorWithAlpha(whiteColor, alpha: 0.05), tintColor: colorWithAlpha(whiteColor, alpha: 0.5))
setColorForLabels([kitchenLabel, avarageBill, metroLabel, typeLabel, tagsLabel], color: colorWithAlpha(whiteColor, alpha: 0.50))
topName.textColor = whiteColor
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
self.view.backgroundColor = backgroundColorValue
bottomComfitmButton.tintColor = whiteColor
bottomComfitmButton.backgroundColor = colorWithAlpha(whiteColor, alpha: 0.15)
showAllTags.titleLabel!.addCharactersSpacing(-0.39, text: (self.showAllTags.titleLabel?.text)!)
showAllTags.setTitleColor(colorWithAlpha(whiteColor, alpha: 0.5), for: UIControlState())
showAllFilterImage.image = UIImage(named: "filterShowAllDark")
}
fileprivate func customizeLightTheme() {
comfirmButton.setImage(UIImage(named: "comfirmDark"), for: UIControlState())
dismissButton.setImage(UIImage(named: "closeDark"), for: UIControlState())
setColorForLabels([kitchenLabel, avarageBill, metroLabel, typeLabel, tagsLabel], color: colorWithAlpha(grayColor, alpha: 0.50))
topName.textColor = grayColor
setColorsForTableViews([kitchenTableView, metroTableView, typeTableView], separatorColor: colorWithAlpha(grayColor, alpha: 0.1), tintColor: colorWithAlpha(grayColor, alpha: 0.59))
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
bottomComfitmButton.tintColor = grayColor
bottomComfitmButton.backgroundColor = colorWithAlpha(whiteColor, alpha: 0.25)
showAllTags.titleLabel!.addCharactersSpacing(-0.39, text: (self.showAllTags.titleLabel?.text)!)
showAllTags.setTitleColor(colorWithAlpha(grayColor, alpha: 0.5), for: UIControlState())
showAllFilterImage.image = UIImage(named: "filterShowAllLight")
}
fileprivate func setupBillButtons(_ low: Bool, medium: Bool, high: Bool) {
lowBillButton.isSelected = low
mediumBillButton.isSelected = medium
highBillButton.isSelected = high
}
fileprivate func setSeparatorInsets(_ tableViews: [UITableView], edge: UIEdgeInsets) {
for tableView in tableViews {
tableView.separatorInset = edge
}
}
fileprivate func tempConfigButtons(_ buttons: [UIButton]) {
for button in buttons {
button.setTitleColor(whiteColor, for: .selected)
if self.color == themeColor.dark {
button.setBackgroundColor(colorWithAlpha(whiteColor, alpha: 0.50), forState: .selected)
button.setTitleColor(whiteColor, for: UIControlState())
DispatchQueue.main.async(execute: {
button.roundCorners([.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 15, borderColor: self.colorWithAlpha(self.whiteColor, alpha: 0.50), borderWidth: 1)
})
} else {
button.setTitleColor(grayColor, for: UIControlState())
button.setBackgroundColor(colorWithAlpha(grayColor, alpha: 0.50), forState: .selected)
DispatchQueue.main.async(execute: {
button.roundCorners([.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 15, borderColor: self.grayColor, borderWidth: 1)
})
}
}
}

Related

Why bottom line for text field does not follow the constraints rule in Swift?

This is my Utilities file in my project where I set the bottom line for the text field:
import Foundation
import UIKit
class Utilities {
static func styleTextField(_ textfield:UITextField) {
let bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0, y: textfield.frame.height - 2, width: textfield.frame.width, height: 2)
bottomLine.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1).cgColor
textfield.borderStyle = .none
textfield.layer.addSublayer(bottomLine)
}
static func styleFilledButton(_ button:UIButton) {
button.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
button.layer.cornerRadius = 25.0
button.tintColor = UIColor.white
}
static func styleFilledButtonweb(_ button:UIButton) {
button.backgroundColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
button.layer.cornerRadius = 5.0
button.tintColor = UIColor.white
}
static func styleHollowButton(_ button:UIButton) {
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1).cgColor
button.layer.cornerRadius = 25.0
button.tintColor = UIColor.init(red: 255/255, green: 77/255, blue: 0/255, alpha: 1)
}
}
And this is my View Controller file for using the styleTextField function:
import UIKit
import FirebaseAuth
import Firebase
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var firstNameTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Ad"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
firstNameTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var lastNameTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Soyad"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
lastNameTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var emailTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Email"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
emailTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var passwordTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Şifre"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
passwordTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var passworddogrulaTextField: UITextField! {
didSet {
var whitePlaceholderText = NSMutableAttributedString()
let Name = "Şifreyi Doğrula"
whitePlaceholderText = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica Neue", size: 15)!]) // Font
whitePlaceholderText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range:NSRange(location:0,length:Name.count)) // Color
passworddogrulaTextField.attributedPlaceholder = whitePlaceholderText
}
}
#IBOutlet weak var signUpButton: UIButton!
#IBOutlet weak var errorLabel: UILabel!
let Button = UIButton(type: .custom)
let Button1 = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
setUpElements()
show_hide_password(textfield: passwordTextField)
show_hide_password1(textfield: passworddogrulaTextField)
self.passwordTextField.delegate = self
self.passworddogrulaTextField.delegate = self
self.emailTextField.delegate = self
self.lastNameTextField.delegate = self
self.firstNameTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
vself.view.endEditing(true)
return false
}
func show_hide_password(textfield: UITextField) {
textfield.rightViewMode = .unlessEditing
Button.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
Button.imageEdgeInsets = UIEdgeInsets(top: 5, left: -24, bottom: 5, right: 15)
Button.frame = CGRect(x: CGFloat(textfield.frame.size.width - 25), y: CGFloat(5), width: CGFloat(15), height: CGFloat(25))
Button.addTarget(self, action: #selector(self.btnVisibilityClicked), for: .touchUpInside)
textfield.rightView = Button
textfield.rightViewMode = .always
}
func show_hide_password1(textfield: UITextField) {
textfield.rightViewMode = .unlessEditing
Button1.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
Button1.imageEdgeInsets = UIEdgeInsets(top: 5, left: -24, bottom: 5, right: 15)
Button1.frame = CGRect(x: CGFloat(textfield.frame.size.width - 25), y: CGFloat(5), width: CGFloat(15), height: CGFloat(25))
Button1.addTarget(self, action: #selector(self.btnVisibilityClicked1), for: .touchUpInside)
textfield.rightView = Button1
textfield.rightViewMode = .always
}
#IBAction func btnVisibilityClicked(_ sender: Any) {
(sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
if (sender as! UIButton).isSelected{
self.passwordTextField.isSecureTextEntry = false
Button.setImage(UIImage(systemName: "eye.fill"), for: .normal)
} else {
self.passwordTextField.isSecureTextEntry = true
Button.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
}
}
#IBAction func btnVisibilityClicked1(_ sender: Any) {
(sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
if (sender as! UIButton).isSelected{
self.passworddogrulaTextField.isSecureTextEntry = false
Button1.setImage(UIImage(systemName: "eye.fill"), for: .normal)
} else {
self.passworddogrulaTextField.isSecureTextEntry = true
Button1.setImage(UIImage(systemName: "eye.slash.fill"), for: .normal)
}
}
func setUpElements(){
errorLabel.alpha = 0
Utilities.styleTextField(firstNameTextField)
Utilities.styleTextField(lastNameTextField)
Utilities.styleTextField(emailTextField)
Utilities.styleTextField(passwordTextField)
Utilities.styleTextField(passworddogrulaTextField)
Utilities.styleFilledButton(signUpButton)
}
}
Here are the screenshots Connection for the text fields and the screenshot of sign up page storyboard for the storyboards and connections between storyboards and view controller:
Even though I declared the constraints, the bottom line does not appear right. What should I do for it to appear correct?
Here is the screenshot of the wrong appearance: The appearance of the text field in iPhone 12 Pro Max
And here is the screenshot of the correct appearance in the simulator of Xcode for iPhone 11: The simulator of iPhone 11 and the correct appearance
Thank you for your help! Here is the video link for the draft.
You are setting these before layouts set. If you had your view in a UIView class you could put these in layoutSubviews()
Since you are setting these in viewController, putting setUpElements() into viewDidAppear() will probably solve your problem.

How can I create a custom segment-top-tab view controller? (Swift)

I have a 2 segment-top-tab-VC class, thanks to someone in SOF.
The screenshots are below.
// The 2 segment-top-tab-VC
class SegmentTabVC: UIViewController {
//MARK: - Properties
let viewControllers: [UIViewController]
init(viewControllers: [UIViewController], nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
self.viewControllers = viewControllers
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let leftButton: UIButton = {
let bt = UIButton()
bt.addTarget(self, action: #selector(switchTabs), for: .touchUpInside)
bt.setAttributedTitle(NSMutableAttributedString(string: "미팅", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).darker(componentDelta: 0.4)]), for: .selected)
bt.setAttributedTitle(NSMutableAttributedString(string: "미팅", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).lighter(componentDelta: 0.4)]), for: .normal)
bt.tag = 0
return bt
}()
private let rightButton: UIButton = {
let bt = UIButton()
bt.addTarget(self, action: #selector(switchTabs), for: .touchUpInside)
bt.setAttributedTitle(NSMutableAttributedString(string: "번개", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).darker(componentDelta: 0.4)]), for: .selected)
bt.setAttributedTitle(NSMutableAttributedString(string: "번개", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).lighter(componentDelta: 0.4)]), for: .normal)
bt.tag = 1
return bt
}()
private let contentView: UIView = {
let view = UIView()
return view
}()
var currentVC: UIViewController?
lazy var bannerTabVC = viewControllers[0]
lazy var gravitySliderTabVC = viewControllers[1]
//MARK: - Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
leftButton.isSelected = true
displayCurrentTab(0)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let currentVC = currentVC {
currentVC.viewWillDisappear(animated)
}
}
//MARK: - Selectors
#objc func switchTabs(_ sender: UIButton) {
self.currentVC!.view.removeFromSuperview()
self.currentVC!.removeFromParent()
switch sender.tag {
case 0:
rightButton.isSelected = false
leftButton.isSelected = true
case 1:
rightButton.isSelected = true
leftButton.isSelected = false
default:
return
}
displayCurrentTab(sender.tag)
}
//MARK: - Helpers
func configureUI() {
view.backgroundColor = .white
let stack = UIStackView(arrangedSubviews: [leftButton, rightButton])
stack.axis = .horizontal
stack.distribution = .fillEqually
view.addSubview(stack)
stack.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 50)
view.addSubview(contentView)
contentView.anchor(top: stack.bottomAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor)
}
func displayCurrentTab(_ tabIndex: Int){
if let vc = viewControllerForSelectedSegmentIndex(tabIndex) {
self.addChild(vc)
vc.didMove(toParent: self)
vc.view.frame = self.contentView.bounds
self.contentView.addSubview(vc.view)
self.currentVC = vc
}
}
func viewControllerForSelectedSegmentIndex(_ index: Int) -> UIViewController? {
var vc: UIViewController?
switch index {
case 0 :
vc = viewControllers[0]
case 1 :
vc = viewControllers[1]
default:
return nil
}
return vc
}
}
2 segment-top-tab-VC screenshot
2 segment-top-tab-VC screenshot
The above code worked.
Now, I would like to make a custom segment-top-tab-VC class for N-segments.
I'm not used to making custom classes. Can somebody help me out?
Below is the code I'm struggling with...
class Utilities {
func segmentButton(_ title: String, _ tag: Int) -> UIButton {
let bt = UIButton()
bt.setAttributedTitle(NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).darker(componentDelta: 0.4)]), for: .selected)
bt.setAttributedTitle(NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.1393318772, green: 0.1493551731, blue: 0.2001486421, alpha: 1).lighter(componentDelta: 0.4)]), for: .normal)
bt.tag = tag
return bt
}
}
class SegmentTabVC: UIViewController {
//MARK: - Properties
let viewControllers: [UIViewController]
let titles: [String]
let buttons: [UIButton]
var currentIndex: Int
init(viewControllers: [UIViewController], titles: [String], nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
self.viewControllers = viewControllers
self.titles = titles
for index in 0 ..< viewControllers.count {
let button = Utilities().segmentButton(titles[index], index)
button.addTarget(self, action: #selector(switchTabs), for: .touchUpInside)
self.buttons.append(button)
}
self.currentIndex = 0
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
...
}
For anyone who struggles with the same problem in the future:
import UIKit
class SegmentTabVC: UIViewController {
//MARK: - Properties
let viewControllers: [UIViewController]
let titles: [String]
init(viewControllers: [UIViewController], titles: [String], nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
self.viewControllers = viewControllers
self.titles = titles
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var currentIndex: Int = 0
var buttons: [UIButton] = []
var topView: UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.7254901961, green: 0.6705882353, blue: 0.9607843137, alpha: 1)
return view
}()
private let contentView = UIView()
var currentVC: UIViewController?
//MARK: - Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
prepareButtons()
configureUI()
buttons[0].isSelected = true
displayCurrentTab(currentIndex)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let currentVC = currentVC {
currentVC.viewWillDisappear(animated)
}
}
//MARK: - Selectors
#objc func switchTabs(_ sender: UIButton) {
self.currentVC!.view.removeFromSuperview()
self.currentVC!.removeFromParent()
buttons[currentIndex].isSelected = false
buttons[sender.tag].isSelected = true
currentIndex = sender.tag
displayCurrentTab(currentIndex)
}
//MARK: - Helpers
func createButton(_ index: Int) -> UIButton {
let button = Utilities().segmentButton(titles[index], index)
button.addTarget(self, action: #selector(switchTabs), for: .touchUpInside)
return button
}
func prepareButtons() {
for index in 0 ..< viewControllers.count {
buttons.append(createButton(index))
}
}
func configureUI() {
navigationController?.navigationBar.isHidden = true
view.backgroundColor = .white
let safeTopView = UIView()
safeTopView.backgroundColor = #colorLiteral(red: 0.7254901961, green: 0.6705882353, blue: 0.9607843137, alpha: 1)
view.addSubview(safeTopView)
safeTopView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.topAnchor, right: view.rightAnchor)
view.addSubview(topView)
topView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 56)
let stack = UIStackView(arrangedSubviews: buttons)
stack.axis = .horizontal
stack.distribution = .fillEqually
view.addSubview(stack)
stack.anchor(top: topView.bottomAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 44)
let dividerView = UIView()
dividerView.backgroundColor = .systemGray6
view.addSubview(dividerView)
dividerView.anchor(top: stack.bottomAnchor, left: view.leftAnchor, right: view.rightAnchor, height: 0.75)
view.addSubview(contentView)
contentView.anchor(top: dividerView.bottomAnchor, left: view.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.rightAnchor)
}
func displayCurrentTab(_ tabIndex: Int){
let selectedVC = viewControllers[tabIndex]
self.addChild(selectedVC)
selectedVC.didMove(toParent: self)
selectedVC.view.frame = self.contentView.bounds
self.contentView.addSubview(selectedVC.view)
self.currentVC = selectedVC
}
}
import UIKit
class MeetVC: SegmentTabVC {
//MARK: - Properties
init() {
super.init(viewControllers: [MY_VC_0(), MY_VC_1(), MY_VC_2(), MY_VC_3()], titles: ["MY_TITLE_0", "MY_TITLE_1", "MY_TITLE_2", "MY_TITLE_3"])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Life Cycles
//MARK: - Selectors
//MARK: - Helpers
override func configureUI() {
super.configureUI()
// Whatever..
}
}

UIKit - adding layer effect to button removes image

I have a "fake" check box that I made using UIButton and:
var mCheckState: Bool = false {
didSet {
if mCheckState == true {
self.setImage(checkedImage, for: UIControl.State.normal)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
}
}
}
But when I create this layer style to add shadow/highlight edge:
contentHorizontalAlignment = .left;
contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
setTitleColor(.black, for: UIControl.State.normal)
setTitleColor(UIColor(red: 0.85, green: 0.70, blue: 0.65, alpha: 1.0), for: UIControl.State.highlighted)
layer.backgroundColor = globalColorCG_white_background
layer.shadowColor = CGColor(gray: 1.0, alpha: 1.0)
layer.shadowOpacity = 0.8
layer.shadowRadius = globalButtonRadiusShadow * 0.75
layer.cornerRadius = globalButtonRadiusShadow
layer.shadowOffset = CGSize(width: -6.0,height: -8.0)
layer2 = CALayer(layer: layer)
layer2!.backgroundColor = globalColorCG_white_background
layer2!.shadowColor = CGColor(gray: 0.0, alpha: 1.0)
layer2!.shadowOpacity = 0.1
layer2!.shadowRadius = globalButtonRadiusShadow * 0.5
layer2!.cornerRadius = globalButtonRadiusShadow
layer2!.shadowOffset = CGSize(width: 6.0, height: 8.0)
layer2!.frame = layer.bounds
layer.insertSublayer(layer2!, at: 0)
showsTouchWhenHighlighted = true
...the image no longer renders. What should I add/fix to get the image to render again? :- )
Extra code for info:
let checkedImage = UIImage(systemName: "checkmark.square")! as UIImage
let uncheckedImage = UIImage(systemName: "square")! as UIImage
var mIsCheckBox = false
var mCheckState: Bool = false {
didSet {
if mCheckState == true {
self.setImage(checkedImage, for: UIControl.State.normal)
//self.bringSubviewToFront(checkedImage)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
//self.bringSubviewToFront(uncheckedImage)
}
}
}
You can bring to front your image
class ButtonSubclass: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
/**
Set other button property and layers.
*/
if let imgView = imageView {
self.bringSubviewToFront(imgView)
}
}
}
You need to add your layer2 below the button's ImageView layer.
So change this line:
layer.insertSublayer(layer2!, at: 0)
To this:
layer.insertSublayer(layer2!, below: imageView!.layer)
You may want to check the button's imageView isn't nil and in cases where it is just add as you have already:
if let imageViewLayer = imageView?.layer {
layer.insertSublayer(layer2!, below: imageViewLayer)
} else {
layer.insertSublayer(layer2!, at: 0)
}

can't set up UISwitch in Swift 4

Getting rustily back into iOS programming after some years away and am having trouble setting up a UISwitch. Here's my code:
#IBOutlet weak var firstConjugationVerbSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
firstConjugationVerbSwitch.addTarget(self, action: #selector(changeText), for: .valueChanged)
}
#objc func changeText() {
print("changeText function running.")
}
The error I get when I toggle the switch is
[Latin_Substitution_Drills.VerbOptionsViewController firstConjugationVerbSwitch:]: unrecognized selector sent to instance 0x7ffcea817600
Any thoughts about what I'm doing wrong?
let customSwitch = UISwitch(frame:CGRect(x: 20, y: 20, width: 0, height: 0))
customSwitch.isOn = false
customSwitch.onTintColor = UIColor(red: 10/255, green: 105/255, blue: 122/255, alpha: 1)
//customSwitch.setOn(true, animated: true)
customSwitch.transform = CGAffineTransform(scaleX: 0.60, y: 0.60)
customSwitch.addTarget(self, action: #selector(switchTarget(sender:)), for: .valueChanged)
let switchButton = UIBarButtonItem(customView: customSwitch)
#objc func switchTarget(sender: UISwitch!)
{
if sender.isOn {
// do something ..
} else{
// do something ..
}
}

Sigabrt when trying to display another view controller

I want to go to another view controller when pressing button my btnSignUp, If I write code like this I have error "sigabrt". What I should do?
import UIKit
import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 15/255, green: 52/255, blue: 100/255, alpha: 1)
createTop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createTop() {
let topView = UIView()
self.view.addSubview(topView)
topView.backgroundColor = UIColor(red: 15/255, green: 52/255, blue: 100/255, alpha: 1)
topView.snp_makeConstraints { (make) -> Void in
make.width.equalTo((self.view.frame.width/10)*8)
make.height.equalTo(self.view.frame.height/5)
make.centerX.equalTo(self.view)
make.top.equalTo(self.view).offset(self.view.frame.height/15)
}
let btnSignUp = UIButton()
self.view.addSubview(btnSignUp)
btnSignUp.backgroundColor = UIColor(red: 15/255, green: 52/255, blue: 100/255, alpha: 1)
btnSignUp.layer.borderColor = UIColor.whiteColor().CGColor
btnSignUp.layer.borderWidth = 1
btnSignUp.layer.cornerRadius = 6
btnSignUp.setTitle("Sign Up", forState: UIControlState.Normal)
btnSignUp.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17)
btnSignUp.snp_makeConstraints { (make) -> Void in
make.width.equalTo(((self.view.frame.width/10)*7)+40)
make.height.equalTo(self.view.frame.height/13)
make.top.equalTo(ORView.snp_bottom).offset(20)
make.centerX.equalTo(self.view)
}
btnSignUp.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)
func buttonAction(sender:UIButton!)
{
let signUpVC = SignUpViewController()
self.presentViewController(signUpVC, animated: true, completion: nil)
}
}
}
Your action selector buttonAction doesn't match your function declaration - It takes an argument, so the selector will be buttonAction:
btnSignUp.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
Additionally, check your parentheses. It appears that your buttonAction function is declared inside func createTop()
func createTop() {
let topView = UIView()
self.view.addSubview(topView)
topView.backgroundColor = UIColor(red: 15/255, green: 52/255, blue: 100/255, alpha: 1)
topView.snp_makeConstraints { (make) -> Void in
make.width.equalTo((self.view.frame.width/10)*8)
make.height.equalTo(self.view.frame.height/5)
make.centerX.equalTo(self.view)
make.top.equalTo(self.view).offset(self.view.frame.height/15)
}
let btnSignUp = UIButton()
self.view.addSubview(btnSignUp)
btnSignUp.backgroundColor = UIColor(red: 15/255, green: 52/255, blue: 100/255, alpha: 1)
btnSignUp.layer.borderColor = UIColor.whiteColor().CGColor
btnSignUp.layer.borderWidth = 1
btnSignUp.layer.cornerRadius = 6
btnSignUp.setTitle("Sign Up", forState: UIControlState.Normal)
btnSignUp.titleLabel?.font = UIFont(name: "AvenirNext-Regular", size: 17)
btnSignUp.snp_makeConstraints { (make) -> Void in
make.width.equalTo(((self.view.frame.width/10)*7)+40)
make.height.equalTo(self.view.frame.height/13)
make.top.equalTo(ORView.snp_bottom).offset(20)
make.centerX.equalTo(self.view)
}
btnSignUp.addTarget(self, action: "buttonAction", forControlEvents: UIControlEvents.TouchUpInside)
}
func buttonAction(sender:UIButton!) {
let signUpVC = SignUpViewController()
self.presentViewController(signUpVC, animated: true, completion: nil)
}
Finally, I doubt that you want to get your new view controller by SignUpViewController() - if you are using a storyboard you want to call instantiateViewControllerWithIdentifier

Resources