Position “Clear Button” in UITextfield

余生颓废 提交于 2019-12-12 15:42:44

问题


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)
        }
    }`


回答1:


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)

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

Hope this will help.




回答2:


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)
    }
}


来源:https://stackoverflow.com/questions/57787658/position-clear-button-in-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!