Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position "Clear Button" in UITextfield

Is there a way to position the clear button? I would like to move it down by just a little bit so it's on the same level with the text input. Any ideas?

My Textfields are already Subclasses of another Class that handles the effects. Including the "clearButtonRect" function doesn't work.

@IBDesignable open class HoshiTextField: TextFieldEffects {

//effect functions..

    override open func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: 0, y: 0.2, width: 0.1, height: 0.3)
        }
    }`

like image 668
Chris Avatar asked Sep 04 '19 11:09

Chris


2 Answers

Subclass your textfield and override the clearButtonRect function

class CustomTextField: UITextField {

    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: xPos, y:yPos, width: yourWidth, height: yourHeight)
    }
}

EDIT 1 - Subclass 3rd party Textfield

As you are using 3rd party library calls TextFieldEffects you will need to follow the below steps.

If you you are using storyboard and have a textfield on there (set the class to CustomTextField)

Setting CustomTextField Class

if you can doing it programmatically you will need to change it there.

Then create a new swift file call it CustomTextField.swift and add the below code

import UIKit
import TextFieldEffects // Import the 3rd party library

// Now you are subclassing the 3rd party textfield
// Change it to the textfield you are using and if you are using multiple create subclass for individual ones.
class CustomTextField: HoshiTextField {

    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        // change the return line as per your requirement. 
        return CGRect(x: 300, y: 25, width: 40, height: 20) 
    }
}

Output

Output Image

Hope this will help.

like image 93
chirag90 Avatar answered Oct 15 '22 10:10

chirag90


You can create your own custom text field

Chirag's answer is correct but according to Apple, your method should call the super implementation and modify the returned rectangle’s origin only

class CustomTextField : UITextField
{
    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect{
        let rect = super.clearButtonRect(forBounds: bounds)
        return rect.offsetBy(dx: customX, dy: customY)
    }
}
like image 28
Manav Avatar answered Oct 15 '22 09:10

Manav