Text field leftview image color - swift

how can I change the leftview image color while the user is using the keyboard? I want the image to be red if the userNameTextField doesn't contain 6 letter.
Thank you very much
here's my code for the leftview image:
userNameTextField.leftViewMode = UITextFieldViewMode.Always
userNameTextField.leftView = UIImageView(image: UIImage(named: "Clipboard-20-2"))

Just add a target to your UITextField for control event EditingChanged and check if the sender character count is less than 6. You also need to set your image rendering mode to always template and set your UITextField leftView tintColor property to red:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var userNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let templateImage = UIImage(named: "Clipboard-20-2")?.imageWithRenderingMode(.AlwaysTemplate) { // it will only use your image silhouette tinted with blue or red color
let imageView = UIImageView(image: templateImage)
imageView.tintColor = UIColor.redColor()
userNameTextField.leftViewMode = .Always
userNameTextField.leftView = imageView
}
userNameTextField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
func textChanged(sender: UITextField) {
sender.leftView?.tintColor = sender.text?.characters.count < 6 ? UIColor.redColor() : nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

Is there a way to make a completely transparent UIButton that works?

I've a custom UINavigationItem title view. It has a label pushed to the top of it, which I've enabled to respond to .touchDown and send an action.
However, the taps don't register near the top of the label, presumably because the active region is clipped. So I configured another invisible view (not in navigation item), and set it up as a control, and positioned it above that navigation title view label.
However, it doesn't work unless I set the 'invisible' view's alpha to at least 0.02, because Apple seems to intentionally disable action for a view with an alpha less than that. Unfortunately, against a black screen in dark mode, the 'invisible' hitpad view shows up as a slightly grey rectangle, which is not a good aesthetic.
I guess I could go to some lengths to try to make the button background color match the screen background at that location, but it seems a bit tacky.
What alternatives might I have?
You can simply create a blank png image, and add it in top of your title view. make sure to set the imageView and the title view isUserInteractionEnabled properties to true:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
let imageView = UIImageView()
imageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(
target: self,
action: #selector(tap)
)
imageView.addGestureRecognizer(tap)
imageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
imageView.image = UIImage(named: "blank")
let titleLabel = UILabel()
titleLabel.text = "Transparent Button"
titleLabel.autoresizingMask = [.flexibleHeight, .flexibleWidth]
titleLabel.addSubview(imageView)
navigationItem.titleView = titleLabel
navigationItem.titleView?.isUserInteractionEnabled = true
}
#objc func tap(_ gesture: UITapGestureRecognizer) {
print(#function)
}
}
Sample project
You can also just add your gesture recognizer directly to your titleView. No need for the transparent image at all unless you need to control the area of the gesture:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .green
let tap = UITapGestureRecognizer(
target: self,
action: #selector(tap)
)
let titleLabel = UILabel()
titleLabel.text = "Transparent Button"
titleLabel.autoresizingMask = [.flexibleHeight, .flexibleWidth]
titleLabel.addGestureRecognizer(tap)
navigationItem.titleView = titleLabel
navigationItem.titleView?.isUserInteractionEnabled = true
}
#objc func tap(_ gesture: UITapGestureRecognizer) {
print(#function)
}
}
This is an adaptation of the #LeoDabus' Accepted answer that works. However it was utterly informed by his explanation and example. The only meaningful change I made to Leo's example was to create a real empty image programmatically, and drop the label generation. Without a real empty UIImage(), the only way to make taps on the region work that I found is to set the image view's background color to non-clear.
func emptyImage(with size: CGSize) -> UIImage?
{
UIGraphicsBeginImageContext(size)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func configureButtons() {
let imageView = UIImageView(image: emptyImage(with: CGSize(width: view.frame.size.width - 250, height: 44)))
imageView.frame = CGRect(x: 140, y: self.view.safeAreaInsets.top + 50,
width: view.frame.size.width - 250, height: 44)
imageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(actionEnableTitleEditing))
imageView.addGestureRecognizer(tap)
imageView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(imageView)
}

Programmatic UITextField not visible on viewDidLoad

I am trying create a UITextField programmatically, however it does not appear in the view.
I believe I have set the constraints correctly and they should all be activated on viewDidLoad. I am sure I have missed something obvious however for the life of me cannot understand what.
class HomeController: UIViewController {
let textField: UITextField = {
let input = UITextField()
input.translatesAutoresizingMaskIntoConstraints = false
return input
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .purple
view.addSubview(textField)
NSLayoutConstraint.activate([
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
textField.centerYAnchor.constraint(equalTo: view.centerYAnchor),
textField.widthAnchor.constraint(equalToConstant: 300),
textField.heightAnchor.constraint(equalToConstant: 40)
])
}
}
Set a background property and it will show.
let textField: UITextField = {
let input = UITextField()
input.backgroundColor = UIColor.white
input.translatesAutoresizingMaskIntoConstraints = false
return input
}()

Same color for StatusBar and NavigationBar iOS

I added navigationBar manualy from controls
How to make StatusBar Backgroud color = same as navigationBar
Try this code: Tested in Swift 3
#IBOutlet weak var navBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
navBar.barTintColor = UIColor.black // Set any colour
navBar.isTranslucent = false
navBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:UIFont(name:"HelveticaNeue", size: 16)!]
let barView = UIView(frame: CGRect(x:0, y:0, width:view.frame.width, height:UIApplication.shared.statusBarFrame.height))
barView.backgroundColor = UIColor.black
view.addSubview(barView)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
Updated to clear down voters

swift hiding label when a button is pressed

I have created my own label and my own button. Now when the page loads the label hides as I want but when i click the button it does not show up as it supposed to do, in fact it does not do anything. How can I fix this problem which is making label show when i press the button?
#IBOutlet var thumbsUpButtonaPressed : UIButton!
#IBOutlet weak var label : UILabel!
override func viewDidLoad() {
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "00000"
self.view.addSubview(label)
label.hidden = true
let buttona = UIButton()
buttona.frame = CGRectMake(0.772 * view.bounds.width, 0.32 * view.bounds.height, 22, 22)
buttona.layer.cornerRadius = 0.04 * view.bounds.width
buttona.backgroundColor = UIColor.greenColor()
buttona.setImage(UIImage(named:"A.png"), forState: .Normal)
buttona.addTarget(self, action: "thumbsUpButtonaPressed", forControlEvents: .TouchUpInside)
view.addSubview(button)
func thumbsUpButtonaPressed(sender: UIButton!) {
label.hidden = false
}
}
I am using below code on swift 3
label.isHidden = true // hide
label.isHidden = false // show
you can use isHidden with other ui objects, see that answer also
Unless I am missing something in viewDidLoad you are creating a new label
var label = ...
you are not using the IBOutlet Property like
label = ...
Also are you sure your brackets are correct because it looks like your buttonPressed method is nested inside viewDidLoad.
Create an IBAction:
#IBAction func thumbsUpButtonaPressed(sender: UIButton) {
label.hidden = false
}
Then connect it with your button by cmd + drag on the button to the action:
Swift 5 Update
#IBAction func thumbsUpButtonaPressed(sender: UIButton) {
label.isHidden = false
}
You can also change:
label.alpha = 1.0 // show
label.alpha = 0.0 // hide
Try to correct your function with:
func thumbsUpButtonaPressed(sender: UIButton!) {
print("button was pressed")
label.hidden = false
label.setNeedDisplay()
}
Create normal IBAction for your button:
#IBAction func thumbsUpButtonaPressed(sender: UIButton!) {
label.hidden = false
}

How to hide keyboard with programmatically created uitextfield

I've programmatically created a uitextfield called "myTextField" in "viewDidLoad".
When I create a function to hide the keyboard when the user taps anywhere on the screen, "myTextField" isn't recognized by xcode. Is it because the textfield is created inside "viewDidLoad"?
Is there any way to access and use "myTextField" outside "viewDidLoad"?
Update: I finally had a chance to go home and copy my code to show what I mean. Here is my code:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Prepare keyboard notifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardDidHideNotification, object: nil);
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width;
let screenHeight = screenSize.height;
let myTextView : UITextField = UITextField(
frame : CGRect(x:10, y:(screenHeight/2), width:(screenWidth-20), height: (screenHeight/3) ) )
myTextView.backgroundColor = UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )
self.scrollView.addSubview( myTextView )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Call this method somewhere in your view controller setup code.
func keyboardWillShow(sender: NSNotification) {
let dict:NSDictionary = sender.userInfo as NSDictionary
let s:NSValue = dict.valueForKey(UIKeyboardFrameEndUserInfoKey) as NSValue;
let rect :CGRect = s.CGRectValue();
self.scrollView.contentOffset = CGPoint(x: 0, y: rect.height)
}
func keyboardWillHide(sender: NSNotification) {
let dict:NSDictionary = sender.userInfo as NSDictionary
let s:NSValue = dict.valueForKey(UIKeyboardFrameBeginUserInfoKey) as NSValue;
let rect :CGRect = s.CGRectValue();
self.scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
I've created a UITextView programmatically because I'm struggling with auto layout in Xcode 6. In the meantime I've updated to Xcode beta 5 (from 4) and now even my scrollview is acting weird. So maybe I have to create it with code as well.
How can I access my textview outside of function viewDidLoad?
Declare it as a property of that class, then you can access it from anywhere. Otherwise its scope is limited to the viewDidLoad function and you can't access it from outside.
class YourClass {
var myTextField:UITextField
override func viewDidLoad() {
//init myTextField
}
func test() {
//do something with myTextField
}
}
Use this one to dismiss keyboard :-
UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)