Function to style TextField borders in swift not working - ios

so I am new to Swift and mobile development, I want to make function that Change TextField style so i don't have to write long code for each TextField i have.
This is what I am trying to do :
func borderstyle(TextField : UITextField){
self.TextField.layer.borderColor = UIColor(red: 46/225, green: 204/225, blue: 113/225, alpha: 1).CGColor;
self.TextField.layer.borderWidth = CGFloat(Float(1.0));
self.TextField.layer.cornerRadius = CGFloat(Float(0.0));
}
I think you can get what i am trying to make form the code , the problem is that TextField in the func is read as #IBOutlet while its not.
I want to style any TextField I have with something like this :
borderstyle(UserNameTextField) // UserNameTextField is #IBOutlet
I know that I am doing some kind of mistake there but I want to know whats the best way to solve that.
Thanks.

Why you pass a textField to the function and then you use self.textField inside of it?
Use:
TextField.layer.borderColor = UIColor(red: 46/225, green: 204/225, blue: 113/225, alpha: 1).CGColor;
TextField.layer.borderWidth = CGFloat(Float(1.0));
TextField.layer.cornerRadius = CGFloat(Float(0.0));

Remove the self pointer from the code.
func borderstyle(textField : UITextField){
textField.layer.borderColor = UIColor(red: 46/225, green: 204/225, blue: 113/225, alpha: 1).CGColor;
textField.layer.borderWidth = CGFloat(Float(1.0));
textField.layer.cornerRadius = CGFloat(Float(0.0));
}
NB: As a good naming concept follow camelCase as shown

Related

Is there a way to change all of my IOS App page's Bg Color by using User Defaults?

I am following this tutorial provided on Youtube for: How to Save Data with UserDefaults - Swift
https://www.youtube.com/watch?v=sUhq1vIrRbo
And I have this code that works for one page only and would like to know how to do the same exact thing (changing background color) but for my entire app pages based on the user's choice.
I have tried keeping the checkForStylePreference() in the viewDidLoad()of another page but it did not recognize it. I copy pasted the whole checkForStylePreference() but still other pieces of code were missing. Is the only way to do it is by copy pasting all of the methods of the viewController in all App pages? Or there is a much simpler way as a believe to reduce amount of code? Currently I can change BgColor from white to grey perfectly enter image description here but I don't know how to apply it for all.
This is the code of my NameViewController.swift (the one I've created for the page in the screenshot). Please note that I have 2 more swift files which are SAButton.swift and ConstantStyles.swift (for the colors)
class NameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
nameLbl.text = myString
checkForStylePreference()
}
#IBAction func didChangeStyleSeg(_ sender: UISegmentedControl) {
isDarkMode = sender.selectedSegmentIndex == 1
saveStylePreference()
updateStyle()
}
var myString = String()
#IBOutlet weak var styleSegment: UISegmentedControl!
#IBOutlet weak var nameLbl: UILabel!
var isDarkMode = false
let defaults = UserDefaults.standard
struct Keys {
static let preferDarkMode = "preferDarkMode"
}
func updateStyle(){
UIView.animate(withDuration: 0.4){
// self.view.backgroundColor = self.isDarkMode ? Colors.darkGrey : .white
// UIColor(hue: 287/360, saturation: 15/100, brightness: 85/100, alpha: 1.0)
self.view.backgroundColor = self.isDarkMode ? Colors.lightGrey : .white
//recent correct one
// self.view.backgroundColor = self.isDarkMode ? Colors.darkGrey : .white
//self.view.UIBackgroundFetchResult = self.isDarkMode? UIColor.grey : .white
}
}
func saveStylePreference(){
defaults.set(isDarkMode, forKey: Keys.preferDarkMode)
}
func checkForStylePreference(){
let preferDarkMode = defaults.bool(forKey: Keys.preferDarkMode)
if preferDarkMode{
isDarkMode = true
updateStyle()
styleSegment.selectedSegmentIndex = 1
}
}
// Do any additional setup after loading the view.
}
Code of the SAButton.swift
class SAButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupButton()
}
private func setupButton() {
setTitleColor(.white, for: .normal)
backgroundColor = Colors.lightBlue
titleLabel?.font = .boldSystemFont(ofSize: 20)
layer.cornerRadius = frame.size.height / 2
}
}
Code of the ConstantStyles.swift
import UIKit
struct Colors {
static let darkGrey = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1)
// static let purple = UIColor(red: 212/255, green: 186/255, blue: 86/255, alpha: 1)
static let lightBlue = UIColor(red: 89/255, green: 205/255, blue: 242/255, alpha: 1)
static let darkPurple = UIColor(red: 242/255, green: 232/255, blue: 255/255, alpha: 1.0)
// UIColor(hue: 287/360, saturation: 15/100, brightness: 85/100, alpha: 1.0)
static let lightPurple = UIColor(red: 240/255, green: 229/255, blue: 255/255, alpha: 1.0)
static let lightGrey = UIColor(red: 237/255, green: 237/255, blue: 237/255, alpha: 1.0)
//UIColor(red: 249/255, green: 244/255, blue: 255/255, alpha: 1.0)
}
I believe it could be simple but I am new to Swift, I would like to know what part of code to keep exactly and where. Much appreciated.
Ps: Original project Source Code is provided below the Youtube Video.
You can create a main class and inherit from it
class GeneralVC : UIViewController {
override func viewDidLoad() {
self.view.backgroundColor = .red // read color from userdefaults and set it here
}
}
class ViewController: GeneralVC {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Same applies to any UIKit component that you need to affect globally
Another interesting way to do it is to use Appearance:
Perhaps you can use UIViewControllerWrapperView as a parent.
UIView.appearance(whenContainedInInstancesOf: [UIViewControllerWrapperView]) // UIViewControllerWrapperView might be private. In that case it might take some wizardry to get it to work
Another way to do it is to set it when the UITabBarController or UINavigationController presents a new UIViewController. You can do this by subclassing them.
The reason why I don't like subclassing is that you force a subclass for just one simple thing. If you only do it in a few navigation based ones it's much easier and also easier to override with extensions instead of everything through subclassing.

How to send multiple paramters in perform selector in swift3?

I have to implement perform selector with multiple parameters (two strings parameters). I have created a function.
How to implement this function with perform selector after delay method.
func addBorderLayer(textField: UITextField , placeHolder: String) {
textField.layer.borderColor = UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
textField.layer.borderWidth = 1.0
textField.placeholder = placeHolder
}`
I have call this method like this
self.perform(#selector(SecurityQuestionViewController.clearBorderLayer(textField:placeHolder:)), with:(textField,"Test") , afterDelay: 0.5)
When I pass parameter like this show me segmentation error in xcode,but my problem is how to pass parameters in it.What is correct way to pass parameters?
Use (G)rand (C)entral (D)ispatch, it's block based and easier to use than performSelector, you don't need to call an extra method, change the text field properties directly for example:
func addBorderLayer(textField: UITextField , placeHolder: String) {
textField.layer.borderColor = UIColor.init(colorLiteralRed: 254/255, green: 93/255, blue: 49/255, alpha: 1.0).cgColor
textField.layer.borderWidth = 1.0
textField.placeholder = placeHolder
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
textField.placeholder = "Test"
}
}

How would I change background color of alert view

I am working on tvOS project, I need to create custom alert view with particular background color and text.
Finally , I have got the solution,
if let next = context.nextFocusedView as? UIButton {
next.setTitleColor(UIColor.blackColor(), forState: UIControlState.Focused)
next.backgroundColor = UIColor(red: 248/255, green: 175/255, blue: 2/255, alpha: 1.0)

canDisplayBannerAds causes functionality not to work?

So I have an app that on buttonPressed() the apps background view color changes. All worked fine until I added iAds to monetize.
Essentially, calling:
self.canDisplayBannerAds = true
causes the background color to stop changing. When I comment it out it works, and I could just probably comment it out and move on. But I want to understand why it is causing it stop certain functionality. Thanks!
Function to change button color:
view.backgroundColor = getRandomColor()
func getRandomColor() -> UIColor{
var randomRed:CGFloat = CGFloat(drand48())
var randomGreen:CGFloat = CGFloat(drand48())
var randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
Try adding this:
originalContentView.backgroundColor = getRandomColor

How can I properly group and minimize style code for UITextfields?

I'm trying to implement a standard universal styling of my text fields based strictly on the login/sign up fields.
So, I designed them all to be identical, but I think that I'm reusing a lot of code that can be condensed and maybe used in a variable? I'm not sure how to do so.
The way it is works, but i'm sure it can be done better than this. I'm almost certain there's a way to minimize this code for better practice.
I'm still learning, so I really want to learn better practice in dev.
Here's an example of my sign up view & the styling of the fields:
class JoinVC: UIViewController, UITextFieldDelegate {`
#IBOutlet weak var enterEmailTextField: UITextField!
#IBOutlet weak var enterPasswordTextField: UITextField!
#IBOutlet weak var enterNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Field Border Corner + Width
self.enterEmailTextField.layer.cornerRadius = 24.0
self.enterEmailTextField.layer.borderWidth = 1.5
self.enterPasswordTextField.layer.cornerRadius = 24.0
self.enterPasswordTextField.layer.borderWidth = 1.5
self.enterNameTextField.layer.cornerRadius = 24.0
self.enterNameTextField.layer.borderWidth = 1.5
// ...
// Field Placeholder ColorEnter
var placeholderEnterEmail = NSAttributedString(string: "Enter Email", attributes: [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)])
var placeholderEnterPass = NSAttributedString(string: "Choose Password", attributes: [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)])
var placeholderEnterName = NSAttributedString(string: "Choose Username", attributes: [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)])
enterEmailTextField.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
enterPasswordTextField.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
enterNameTextField.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
// ...
// Text Field Border color
var borderColor : UIColor = UIColor( red: 255, green: 255, blue:255, alpha: 0.8 )
self.enterPasswordTextField.layer.borderColor = borderColor.CGColor; enterEmailTextField.attributedPlaceholder = placeholderEnterEmail;
self.enterEmailTextField.layer.borderColor = borderColor.CGColor; enterPasswordTextField.attributedPlaceholder = placeholderEnterPass;
self.enterNameTextField.layer.borderColor = borderColor.CGColor; enterNameTextField.attributedPlaceholder = placeholderEnterName;
// ...
}
}
The way I have solved this before, especially if all text fields in the project are:
Always going to have identical attributes,
Always going to be created from the storyboard
is to subclass UITextField and apply the attributes in -awakeFromNib:
class KBTextField: UITextField {
let myAttributes = [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)]
let mySublayerTransform = CATransform3DMakeTranslation(20, 0, 0)
let myBorderColor = UIColor( red: 255, green: 255, blue:255, alpha: 0.8 )
override func awakeFromNib () {
self.layer.sublayerTransform = mySublayerTransform
self.layer.borderColor = myBorderColor.CGColor
self.layer.cornerRadius = 24.0
self.layer.borderWidth = 1.5
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: myAttributes)
}
}
Then you can just set the class right on the storyboard (to KBTextField, in this case) and it will take care of all your attributes automatically.
This way, you can ensure that all KBTextFields in your app look identical, as long as you create them through the storyboard.
easy solution for reusable code is a handler
func setupTextField(textField : UITextField, placeHolderString: String)
{
let borderColor = UIColor( red: 1.0, green: 1.0, blue:1.0, alpha: 0.8 )
textField.layer.cornerRadius = 24.0
textField.layer.borderWidth = 1.5
textField.layer.sublayerTransform = CATransform3DMakeTranslation(20, 0, 0);
textField.layer.borderColor = borderColor.CGColor;
textField.attributedPlaceholder = NSAttributedString(string: placeHolderString, attributes: [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)])
}
override func viewDidLoad() {
super.viewDidLoad()
setupTextField(enterEmailTextField, placeHolderString: "Enter Email")
setupTextField(enterPasswordTextField, placeHolderString: "Choose Password")
setupTextField(enterNameTextField, placeHolderString: "Choose Username")
}
Note: UIColor values must be in the range of 0.0 to 1.0
You can use the Extension functionality.
Just create an Extension of UITextField an place your code into that Extension
(easy tutorial here)
Ex:
extension UITextField
{
func setPlaceholderColorAndString(pholder: String, color: UIColor)
{
self.attributedPlaceholder = NSAttributedString(string:pholder,
attributes:[NSForegroundColorAttributeName: color])
}
func setupField()
{
self.layer.cornerRadius = 24.0
self.layer.borderWidth = 1.5
}
}
Then in your code you can use it like:
self.enterEmailTextField.setPlaceholderColorAndString(pholder: "Enter Email", color: UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)
self.enterEmailTextField.setupField()
self.enterPasswordTextField.setPlaceholderColorAndString(pholder: "Enter Password", color: UIColor(red: 255/255, green: 255/255, blue:255/255, alpha: 0.6)
self.enterPasswordTextField.setupField()
And so on. Of course the above snippet it's only to give you an idea how using it, you can improve it a lot to fit your needs.

Resources