How to change border thickness of UISearchBar? - ios

I'm trying to make my search bar look like this
A white background with a thin grey border.
On Xcode, I can set Search style to default (which gives the white background) and Bar tint to grey (which gives the grey border.)
But the result I get is this
How do I change the thickness of the bar to reflect the design I'm going for?
(also, is there a way to change just the font of the search bar? I only found ways to change the font size)

Follow this below steps -
1.Choose UITextField from the object library
2.Drag to your storyboard
3.Choose border style as none.
4.Create a Swift file and add this below extension -
extension UIView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
extension UIButton {
func roundedButton(){
let maskPAth1 = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [.topLeft , .topRight],
cornerRadii:CGSize(width:8.0, height:8.0))
let maskLayer1 = CAShapeLayer()
maskLayer1.frame = self.bounds
maskLayer1.path = maskPAth1.cgPath
self.layer.mask = maskLayer1
}
}
extension UITextField {
func setLeftPaddingPoints(_ amount:CGFloat){
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
func setRightPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
extension UITextField {
#IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length
} else {
return Int.max
}
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
#objc func checkMaxLength(textField: UITextField) {
guard let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
let substring = prospectiveText[..<indexEndOfText]
text = String(substring)
selectedTextRange = selection
}
}
5.Now you can access this extensions either from storyboard or from code to change the values and see the effects.
6.You can change the corner radius, border width, border colour for UITextField.
Hope this method also helps.

The style UISearchBar.Style.minimal provides no default background color or image
and use UITextFiled instead search bar so you can customise icon location
YourTextFiled.rightView = UIImageView(image: UIImage(named: "search-icon"))
YourTextFiled.rightViewMode = UITextField.ViewMode.always

Related

Right margin of custom clear button in iOS

I create a custom clear button on my text field with a background image set.
I position it on the right view but it always positions with a default margin. What I want is to have a right margin, for example, of 8.
extension UITextField {
func clearButtonWithImage(_ image: UIImage) {
let clearButton = UIButton()
clearButton.setBackgroundImage(image, for: .normal)
clearButton.alpha = 0.25
clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
clearButton.contentMode = .scaleAspectFit
clearButton.addTarget(self, action: #selector(self.clear(sender:)), for: .touchUpInside)
self.rightViewMode = .always
self.clearButtonMode = .never
self.rightView = clearButton
}
#objc func clear(sender: AnyObject) {
self.text = ""
}
}
I use a custom textfield class for changing the style of my textfield on selecting.
My custom Textfield Class:
class customSearchTextField: customTextField {
override var isSelected: Bool {
didSet {
setSelected(isSelected)
}
}
private func setSelected(_ selected: Bool) {
//UIView.animate(withDuration: 0.15, animations: {
self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
self.cornerRadius = selected ? 2.0 : 0.0
if selected {
self.clearButtonWithImage(UIImage())
} else {
self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
}
self.layer.shadowColor = UIColor .customDark.cgColor
self.layer.shadowOpacity = selected ? 0.19 : 0.0
//})
}
}
Tried positioning the image frame but it always stays the same.
You should take a look at rightViewRect(forBounds:) method. Create a subclass of UITextField and custom position and size of clear button inside this method.
For example
class customSearchTextField: customTextField {
override var isSelected: Bool {
didSet {
setSelected(isSelected)
}
}
private func setSelected(_ selected: Bool) {
//UIView.animate(withDuration: 0.15, animations: {
self.transform = selected ? CGAffineTransform(scaleX: 1.05, y: 1.05) : CGAffineTransform.identity
self.cornerRadius = selected ? 2.0 : 0.0
if selected {
self.clearButtonWithImage(UIImage())
} else {
self.clearButtonWithImage(#imageLiteral(resourceName: "icClear"))
}
self.layer.shadowColor = UIColor .customDark.cgColor
self.layer.shadowOpacity = selected ? 0.19 : 0.0
//})
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var rect = super.rightViewRect(forBounds: bounds)
rect.origin.x -= 30 // Assume your right margin is 30
return rect
}
}

How to marquee UITextField placeholder if text longer then the UITextField width?

Is it possible to marquee UITextFiled placeholder, if placeholder text is longer then the size of UITextField width, There are lib for UILabel MarqueeLabel but I am not sure how to marquee placeholder, please provide some suggestion, Or you can explain what is a placeholder is actually, it doesn't look like UILabel
I am using bellow code for CustomTextField with validation error message
import UIKit
#IBDesignable
class CustomTextField: UITextField {
var placeholdertext: String?
#IBInspectable
public var cornerRadius :CGFloat {
set { layer.cornerRadius = newValue }
get {
return layer.cornerRadius
}
}
// Provides left padding for images
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.rightViewRect(forBounds: bounds)
textRect.origin.x -= rightPadding
return textRect
}
#IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
#IBInspectable var isUnderLine:Bool = false
{
didSet{
updateView()
}
}
#IBInspectable var rightImage: UIImage? {
didSet {
updateView()
}
}
func setError(error:String?){
if(error != nil)
{
self.attributedPlaceholder = NSAttributedString(string: error!, attributes: [NSForegroundColorAttributeName: UIColor.red])
}
}
#IBInspectable var leftPadding: CGFloat = 0
#IBInspectable var rightPadding: CGFloat = 0
#IBInspectable var textLeftPadding:CGFloat = 0
#IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
#IBInspectable var underlineColor:UIColor = UIColor.black
{
didSet{
self.updateView()
}
}
private var placeholderColorValue:UIColor = UIColor.lightGray
#IBInspectable public var placeholderColor:UIColor
{
set{
self.attributedPlaceholder = NSAttributedString(string:placeholder!, attributes: [NSForegroundColorAttributeName: newValue])
placeholderColorValue = newValue
}
get{
return placeholderColorValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.setUpView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
}
func setUpView() {
if(rightImage != nil)
{
self.leftViewMode = UITextFieldViewMode.always
let rightImageView:UIImageView = UIImageView(image: rightImage)
rightImageView.frame = CGRect(x: 0, y: 0, width: self.frame.size.height, height: self.frame.size.height)
self.rightView = rightImageView
}
else {
rightViewMode = UITextFieldViewMode.never
rightView = nil
}
}
func updateView() {
if let imageLeft = leftImage {
leftViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = imageLeft
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = UITextFieldViewMode.never
leftView = nil
}
if let imageRight = rightImage {
rightViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = imageRight
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
rightView = imageView
} else {
rightViewMode = UITextFieldViewMode.never
rightView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSForegroundColorAttributeName: color])
if(self.isUnderLine)
{
let underline:UIView = UIView()
underline.frame = CGRect(x: 0, y: self.frame.size.height-1, width: self.frame.size.width, height: 1)
underline.backgroundColor = underlineColor
self.addSubview(underline)
}
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: textLeftPadding, y: 0, width: bounds.width, height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
and using validation as
if (txtField.text != "condtion" ){
txtField.setError(error:"Error message for text field");
valid = false;
txtField.becomeFirstResponder()
}

CALayer border colour and width are not changing?

I have 5 textFields and my requirement is I have to set 0.2 border width initially, after that when tap on edit button I have to change border width from 0.2 to 0.8 and again tap on submit button I have to change border width from 0.8 to 0.2.
The thing is that border colour and width are not changing. Here below is my code:
class EditProductCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
//Create Border Line.
createBorderLine(0.2,UIColor.lightGray)
}
//Create Border Line on Text Field
func createBorderLine(_ width : CGFloat, _ color : UIColor)//_ width : CGFloat, _ color : UIColor)
{
setBottomBorder(textField: InvoiceDate, width: width,color : color)
setBottomBorder(textField: InvoiceNumber, width: width,color : color)
setBottomBorder(textField: modelNumber, width: width,color : color)
setBottomBorder(textField: productName, width: width,color : color)
setBottomBorder(textField: serialNumber, width: width,color : color)
self.layoutSubviews()
}
}
Here is another class:
class EditProductView: BaseViewController {
//TableView
#IBOutlet var tableView: UITableView!
//View Did Load
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = hexStringToUIColor(hex: "#CCCCCC")
tableView.delegate = self
tableView.dataSource = self
//Button Submit
self.btnSubmit.isHidden = true
tableView.bounces = false
tableView.alwaysBounceVertical = false
hideKeyboardWhenTappedAround()
}
//Button Submit
#IBAction func btnSubmitAction(_ sender: Any) {
self.btnSubmit.isHidden = true
let index : NSIndexPath = NSIndexPath(row: 0, section: 0)
let tCell : EditProductCell = self.tableView.cellForRow(at: index as IndexPath) as! EditProductCell
//Change border line
tCell.createBorderLine(0.2, UIColor.lightGray)
tCell.btnEdit.isHidden = false
dismissKeyboard()
}
func btnEditAction()
{
btnSubmit.isHidden = false
let index : NSIndexPath = NSIndexPath(row: 0, section: 0)
let tCell : EditProductCell = self.tableView.cellForRow(at: index as IndexPath) as! EditProductCell
tCell.btnEdit.isHidden = true
//Create border line
tCell.createBorderLine(0.8, UIColor.black)
dismissKeyboard()
}
}
Here is set bottom border method in separate class:
//Set Bottom border line.
func setBottomBorder(textField: UITextField, width: CGFloat,color : UIColor) {
let border = CALayer()
border.name = "BottomBorder"
border.borderColor = color.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width,
width: textField.frame.size.width, height: width)
border.borderWidth = width
textField.borderStyle = UITextBorderStyle.none
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true
}
You can see in my code that button submit and button edit. I am changing border line colour and width. Colour and width are not.
I also tried something in but not able to get width change.
override func layoutSublayers(of layer: CALayer) {
if (layer == self.layer)
{
layer.borderWidth = 0.3
}
}
//MARK:- TextField Delegate
extension EditProductCell : UITextFieldDelegate
{
func textFieldDidBeginEditing(_ textField: UITextField) {
if let sublayers = textField.layer.sublayers {
for layer: CALayer in sublayers {
if layer.name == "BottomBorder" {
layer.removeFromSuperlayer()
}
}
}
setBottomBorder(textField: textField, width: 0.8, color: hexStringToUIColor(hex: "#55ACEE"))
}
//TextField Did End Editing
func textFieldDidEndEditing(_ textField: UITextField) {
if let sublayers = textField.layer.sublayers {
for layer: CALayer in sublayers {
if layer.name == "BottomBorder" {
layer.removeFromSuperlayer()
}
}
}
setBottomBorder(textField: textField, width: 0.8,color : UIColor.black)
textField.resignFirstResponder()
}
//TextField Return Key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField
{
nextField.becomeFirstResponder()
}
else
{
textField.resignFirstResponder()
}
return false
}
}
Swift 4
shape.strokeColor = UIColor.lightGray.cgColor
shape.lineWidth = 1.0
If you try with numbers greater than 1 your code works. I think the border width need to be greater than 1.

Setting the frame of a sublayer inside of layoutSubviews() makes changing it impossible. Any workaround for that?

I'm working on a customizable UITextField (see code below). I have added a border at the bottom (you can set it in the storyboard). However, I had problems setting the frame of the CALayer that this border consists of.
If I set it inside the didSet method of var showBottomBorder it doesn't appear on the screen. I think this is because the frame (of the UITextField) hasn't been calculated yet (maybe didSet gets called before that).
So I moved it to the layoutSubviews() method (see code below). This works perfectly.
But now I have another problem. I can't really change that frame anymore. Every time I change it, it gets reset by layoutSubviews() which I think is called then.
At the bottom of my code, there is the method textFieldDidBeginEditing. In there, I wanted to move up my bottom border (animated). But it doesn't work. The border does not move anywhere. And like I said, I think it's because I set the frame inside the layoutSubviews() method.
Is there a better way to set the frame of the bottom border? A way which allows me to change stuff?
#IBDesignable
class CustomizableTextField: UITextField, UITextFieldDelegate {
// MARK: - Properties
private var bottomBorder = CALayer()
// MARK: - #IBInspectables
#IBInspectable var roundCorners: CGFloat = 0 {
didSet {
self.layer.cornerRadius = roundCorners
self.clipsToBounds = true
}
}
/** -- */
#IBInspectable var borderWidth: CGFloat = 1.0 {
didSet {
self.layer.borderWidth = self.borderWidth
}
}
#IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
self.layer.borderColor = self.borderColor.cgColor
}
}
/** -- */
/** -- */
private var showBottomBorder: Bool = false {
didSet {
switch showBottomBorder {
case true:
bottomBorder.borderColor = self.bottomBorderColor.cgColor
bottomBorder.borderWidth = self.bottomBorderWidth
self.layer.addSublayer(bottomBorder)
self.layer.masksToBounds = true
break
case false:
bottomBorder.removeFromSuperlayer()
break
}
}
}
#IBInspectable var bottomBorderWidth: CGFloat = 1.0 {
didSet {
self.showBottomBorder = false
self.showBottomBorder = true
}
}
#IBInspectable var bottomBorderColor: UIColor = UIColor.white {
didSet {
self.showBottomBorder = false
self.showBottomBorder = true
}
}
/** -- */
/** -- */
// Somwhow, the default panel for my font color doesn't change anything, so I created this
#IBInspectable var fixedFontColor: UIColor = UIColor.white {
didSet {
self.textColor = fixedFontColor
}
}
#IBInspectable var placeholderFontColor: UIColor = UIColor.white {
didSet {
var placeholderTxt = ""
if let txt = self.placeholder {
placeholderTxt = txt
}
self.attributedPlaceholder = NSAttributedString(string: placeholderTxt, attributes: [NSForegroundColorAttributeName: placeholderFontColor])
}
}
/** -- */
// MARK: - Overrides and Initializers
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
super.layoutSubviews()
// HERE
bottomBorder.frame = CGRect(x: 0, y: self.frame.size.height - self.bottomBorderWidth, width: self.frame.size.width, height: self.frame.size.height)
}
// setting the textField delegate to self
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//self.borderStyle = .none
self.delegate = self
}
// MARK: - Events
func textFieldDidBeginEditing(_ textField: UITextField) {
}
You can use and extension on UITextFiled for setting the border.
And keep a reference to it with KVC.
By overriding LayoutSubview, every the layout will change, we'l check if the border exists, if so remove it, and re-create a new one with the new frame:
import UIKit
let MyTopBorder = "myTopBorder"
let MyBottomBorder = "myBottomBorder"
struct Defaults {
static let width = CGFloat(1.0)
static func bottonBorderFrame(view: UIView)->CGRect {
return CGRect(x: CGFloat(0), y: view.frame.size.height - Defaults.width, width: view.frame.size.width, height: view.frame.size.height)
}
static func topBorderFrame(view: UIView)->CGRect {
return CGRect(x: CGFloat(0), y: CGFloat(0) , width: view.frame.size.width, height: Defaults.width)
}
}
extension UITextField
{
func setBottomBorder(color:CGColor)
{
if let isBottomBorder = self.getBottomBorderIfExists() {
isBottomBorder.removeFromSuperlayer()
}
self.setBorderWithFrame(Defaults.bottonBorderFrame(self), color: color, andKey: MyBottomBorder)
}
func setTopBorder(color:CGColor)
{
if let isTopBorder = self.getTopBorderIfExists() {
isTopBorder.removeFromSuperlayer()
}
self.setBorderWithFrame(Defaults.topBorderFrame(self), color: color, andKey: MyTopBorder)
}
func setBorderWithFrame(frame: CGRect, color: CGColor, andKey: String) {
self.borderStyle = UITextBorderStyle.None;
let border = CALayer()
border.borderColor = color
border.frame = frame
border.borderWidth = Defaults.width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
self.layer.setValue(border, forKey: andKey)
}
func removeTopBorder() {
if let isTopBorder = self.getTopBorderIfExists() {
self.layer.setValue(nil, forKey: MyTopBorder)
isTopBorder.removeFromSuperlayer()
}
}
func removeBottomBorder() {
if let isBottomBorder = self.getBottomBorderIfExists() {
self.layer.setValue(nil, forKey: MyBottomBorder)
isBottomBorder.removeFromSuperlayer()
}
}
private func getBorderIfExistsByKey(key: String)->CALayer? {
if let isBorderSet = self.layer.valueForKey(key) {
if let borderIsCALayer = isBorderSet as? CALayer {
return borderIsCALayer
}
}
return nil
}
private func getTopBorderIfExists()->CALayer? {
return self.getBorderIfExistsByKey(MyTopBorder)
}
private func getBottomBorderIfExists()->CALayer? {
return self.getBorderIfExistsByKey(MyBottomBorder)
}
public override func layoutSubviews() {
super.layoutSubviews()
// Update bottom on frame change
if let isBottomBorder = self.getBottomBorderIfExists() {
let borderColor = isBottomBorder .borderColor
self.removeBottomBorder()
self.setBottomBorder(borderColor!)
}
// Update top on frame change
if let isTopBorder = self.getTopBorderIfExists() {
let borderColor = isTopBorder.borderColor
self.removeTopBorder()
self.setTopBorder(borderColor!)
}
}
}
Usage:
let textField = UITextField(frame: CGRect(x: 100,y: 100, width: 100, height: 100))
textField.backgroundColor = UIColor.blueColor() // Thie color is for visulizing better
self.view.addSubview(textField)
textField.setBottomBorder(UIColor.blackColor().CGColor) // Now you have a border
textField.frame = CGRect(x: 150, y: 200, width: 200, height: 200) // And the border updated to the new frame
// Now if you would like to change from bottom to top, simply do this:
textField.removeBottomBorder()
textField.setTopBorder(UIColor.blackColor().CGColor)

Creating and removing border line on textFields

Actually i am trying to change border colour of each text field(By increasing border width) on tap.
I have given textFieldEmailAddress.tag = 1 and textFieldPassword.tag = 2 by using stotyBoard.
I am using UITextFieldDelegate.
Means my requirement is :-
1. when i click on a text field its border colour should be dark blue(width =0.8)
and other text fields border line colour should be light blue (width = 0.4)
If we don't click on a text field its border line colour should be light blue.(width = 0.4).
But i am facing a problem when click on text field first time its working fine ,but just when i tap on another text field ,its giving dark blue border colour.
problem is whaever textfield became 0.8 it's not reverting to 0.4 in UI (means UI is not updating only value is getting updated to 0.4)
Is any thing wrong in delegate method or in my below code :-
//View Did load function
override func viewDidLoad()
{
//Set delegate
self.textFieldEmailAddress.delegate = self
self.textFieldPassword.delegate = self
//Create border line on text email address fields.
self.borderline(textFieldEmailAddress)
//Create border line on text password fields.
self.borderline(textFieldPassword)
}
func textFieldDidBeginEditing(textField: UITextField)
{
switch textField.tag
{
case 1:
self.Darkborderline(textFieldEmailAddress)
break
case 2:
self.Darkborderline(textFieldPassword)
break
default:
break
}
}
func textFieldDidEndEditing(textField: UITextField)
{
switch textField.tag
{
case 1:
self.borderline(textFieldEmailAddress)
break
case 2:
self.borderline(textFieldPassword)
break
default:
break
}
}
//Light blue Border line on text field.
func borderline(textField : UITextField)
{
switch textField.tag
{
case 1:
width = CGFloat(0.40)
let border = CALayer()
border.borderColor = UIColor.blueColor().CGColor
border.frame = CGRect(x: 0, y: textFieldEmailAddress.frame.size.height - width,
width: textFieldEmailAddress.frame.size.width, height: width)
border.borderWidth = width
textFieldEmailAddress.borderStyle = UITextBorderStyle.None
textFieldEmailAddress.layer.addSublayer(border)
textFieldEmailAddress.layer.masksToBounds = true
break
case 2:
width = CGFloat(0.40)
let border = CALayer()
border.borderColor = UIColor.blueColor().CGColor
border.frame = CGRect(x: 0, y: textFieldPassword.frame.size.height - width,
width: textFieldPassword.frame.size.width, height: width)
border.borderWidth = width
textFieldPassword.borderStyle = UITextBorderStyle.None
textFieldPassword.layer.addSublayer(border)
textFieldPassword.layer.masksToBounds = true
break
default: break
}
}
//Dark blue Border line on text field.
func Darkborderline(textField : UITextField)
{
//let border = CALayer()
switch textField.tag
{
case 1:
width = CGFloat(0.80)
let border = CALayer()
border.borderColor = UIColor.blueColor().CGColor
border.frame = CGRect(x: 0, y: textFieldEmailAddress.frame.size.height - width,
width: textFieldEmailAddress.frame.size.width, height: width)
border.borderWidth = width
textFieldEmailAddress.borderStyle = UITextBorderStyle.None
textFieldEmailAddress.layer.addSublayer(border)
textFieldEmailAddress.layer.masksToBounds = true
break
case 2:
width = CGFloat(0.80)
let border = CALayer()
border.borderColor = UIColor.blueColor().CGColor
border.frame = CGRect(x: 0, y: textFieldPassword.frame.size.height - width,
width: textFieldPassword.frame.size.width, height: width)
border.borderWidth = width
textFieldPassword.borderStyle = UITextBorderStyle.None
textFieldPassword.layer.addSublayer(border)
textFieldPassword.layer.masksToBounds = true
break
default: break
}
}
First declare one method to set bottom border to field and use the delegate method of UITextFieldDelegate like this
On viewDidLoad first assign thin border like this to both the fields
override func viewDidLoad() {
super.viewDidLoad()
self.setBottomBorder(self.textFieldEmailAddress, width: 0.4)
self.setBottomBorder(self.textFieldPassword, width: 0.4)
self.setBottomBorder(self.passwordBtn, width: 0.4)
}
func setBottomBorder(view: UIView, width: CGFloat) {
let border = CALayer()
border.name = "BottomBorder"
border.borderColor = UIColor.blueColor().CGColor
border.frame = CGRect(x: 0, y: view.frame.size.height - width,
width: view.frame.size.width, height: width)
border.borderWidth = width
view.borderStyle = UITextBorderStyle.None
view.layer.addSublayer(border)
view.layer.masksToBounds = true
}
func removeBottomBorder(view: UIView) {
if let sublayers = view.layer.sublayers {
for layer: CALayer in sublayers {
if layer.name == "BottomBorder" {
layer.removeFromSuperlayer()
break
}
}
}
}
func textFieldDidBeginEditing(textField: UITextField) {
self.removeBottomBorder(textField)
self.setBottomBorder(textField, width: 0.8)
if (textFieldPassword == textField) {
self.setBottomBorder(self.passwordBtn, width: 0.8)
}
}
func textFieldDidEndEditing(textField: UITextField) {
self.removeBottomBorder(textField)
self.setBottomBorder(textField, width: 0.4)
if (textFieldPassword == textField) {
self.removeBottomBorder(self.passwordBtn)
self.setBottomBorder(self.passwordBtn, width: 0.4)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Try this once .
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
if 1 == textField.tag
{
selectedTextField = textFieldEmailAddress
self.selectedTextField.layer.borderColor = UIColor.blueColor().CGColor
self.selectedTextField.layer.borderWidth = 0.8
self.selectedTextField = textField
self.textFieldPassword.layer.borderColor = UIColor.blueColor().CGColor
self.textFieldPassword.layer.borderWidth = 0.4
return true
}
else if 2 == textField.tag
{
selectedTextField = textFieldPassword
self.selectedTextField.layer.borderColor = UIColor.blueColor().CGColor
self.selectedTextField.layer.borderWidth = 0.8
self.selectedTextField = textField
self.textFieldEmailAddress.layer.borderColor = UIColor.blueColor().CGColor
self.textFieldEmailAddress.layer.borderWidth = 0.4
return true
}
else
{
return false
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
self.selectedTextField.layer.borderColor = UIColor.blueColor().CGColor
self.selectedTextField.layer.borderWidth = 0.4
self.selectedTextField = UITextField()
textField.resignFirstResponder()
return true
}

Resources