如何在UITextField中移动清除按钮?

Jak*_*ake 12 iphone objective-c uitableview uitextfield

出于某种原因,当我将UITextfield添加为tablecell的contentview的子视图时,clearbutton不会与字段中键入的文本对齐,并且会在其下方显示一些内容.有什么方法可以移动clearbutton的文本来阻止这种情况发生吗?谢谢你的帮助,

Wea*_*ish 31

正如@Luda所说,正确的方法是继承UITextField并覆盖- (CGRect)clearButtonRectForBounds:(CGRect)bounds.但是传入方法的边界是视图本身的边界而不是按钮.因此,您应该调用super以获得操作系统提供的大小(以避免图像失真),然后调整原点以满足您的需要.

例如

- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
    CGRect originalRect = [super clearButtonRectForBounds:bounds];
    return CGRectOffset(originalRect, -10, 0); //shift the button 10 points to the left
}
Run Code Online (Sandbox Code Playgroud)

Apple 文档指出:

讨论您不应该直接调用此方法.如果要将清除按钮放在其他位置,可以覆盖此方法并返回新矩形.您的方法应该调用超级实现并仅修改返回的矩形的原点.更改清除按钮的大小可能会导致按钮图像不必要的失真.


two*_*ish 11

Van Du Tran 在 Swift 4 中的回答:

class CustomTextField: UITextField {


override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
    let originalRect = super.clearButtonRect(forBounds: bounds)

    return originalRect.offsetBy(dx: -8, dy: 0)
}
Run Code Online (Sandbox Code Playgroud)

}


Awa*_*yaz 7

斯威夫特 4, 5

子类 UITextField (工作完美,经过测试)

class textFieldWithCrossButtonAdjusted: UITextField {

    override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {

        let originalRect = super.clearButtonRect(forBounds: bounds)

        //move 10 points left

        return originalRect.offsetBy(dx: -10, dy: 0)
    }
}
Run Code Online (Sandbox Code Playgroud)


Lud*_*uda 6

我已经将子类化UITextField并覆盖了该函数clearButtonRectForBounds:.

.H

#import <UIKit/UIKit.h>

@interface TVUITextFieldWithClearButton : UITextField

@end
Run Code Online (Sandbox Code Playgroud)

.M

#import "TVUITextFieldWithClearButton.h"

@implementation TVUITextFieldWithClearButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
}


- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width/2-20 , bounds.origin.y-3, bounds.size.width, bounds.size.height);
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 我低估了其中一个答案.我这样做是因为我认为答案是错误的.我已经评论了为什么我这么认为,我很乐意继续和你谈谈(在相关主题上).最重要的是了解事情是如何正确完成的,而不是你有多酷. (7认同)

Sim*_*ide 3

我还没见过这个,屏幕截图会很有帮助。但是,快速的答案是,您可以检查 UITextField 的子视图数组,找到包含清除按钮的子视图,并调整其frame.origin。

编辑:看来我对这个答案(写于 2010 年)被否决了。这不是“官方”批准的方法,因为您正在操纵私有对象,但 Apple 无法检测到它。主要风险是视图层次结构可能会在某个时刻发生更改。

  • 是的,您无法访问 UITextField 的 .m。此外,您不应该访问它。您可以更改公开的属性或子类。但提供的解决方案是错误的。 (4认同)