UITextfield 中的位置 "Clear Button"

Position "Clear Button" in UITextfield

有没有办法定位清除按钮?我想将它向下移动一点,使其与文本输入处于同一水平。有什么想法吗?

我的文本字段已经是另一个处理效果的 Class 的子类。包括 "clearButtonRect" 函数不起作用。

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

Subclass 您的文本字段并覆盖 clearButtonRect 函数

class CustomTextField: UITextField {

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

编辑 1 - Subclass 第 3 方文本字段

当您使用第 3 方库调用 TextFieldEffects 时,您需要执行以下步骤。

如果您使用的是情节提要并且上面有一个文本字段(将 class 设置为 CustomTextField)

如果您可以通过编程方式执行此操作,则需要在那里进行更改。

然后创建一个新的 swift 文件并将其命名为 CustomTextField.swift 并添加以下代码

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

输出

希望这会有所帮助。

您可以创建自己的自定义文本字段

Chirag 的回答是正确的,但根据 Apple 的说法,您的方法应该调用超级实现并仅修改返回的矩形的原点

class CustomTextField : UITextField
{
    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect{
        let rect = super.clearButtonRect(forBounds: bounds)
        return rect.offsetBy(dx: customX, dy: customY)
    }
}

已经基于此处有用的答案... 并回答有关如何自动找到合适的 x/y 位置的评论。这是我对 TextFieldEffects 库中文本字段的通用扩展的解决方案(我使用的是 YoshikoTextField,但该解决方案应该适用于任何具有浮动在字段上方的占位符的解决方案):

该库中的文本字段有一个占位符矩形,它允许我们获得文本字段上部的高度,这导致了错误的偏移。

import UIKit
import TextFieldEffects

class CustomYoshikoTextField: YoshikoTextField {

    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.clearButtonRect(forBounds: bounds)
        let placeholderHeight = self.placeholderRect(forBounds: bounds).height
        return rect.offsetBy(dx: 0, dy: placeholderHeight * 0.5)
    }
}

这只是将清除按钮向下移动了占位符矩形高度的一半。对于任何文本字段大小,保证以字段的实际输入部分为中心。