繁体   English   中英

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

[英]How can I move the clear button in a UITextField?

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

正如@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
}

Apple 文档指出:

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

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

。H

#import <UIKit/UIKit.h>

@interface TVUITextFieldWithClearButton : UITextField

@end

.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

子类UITextField并覆盖此方法:

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.origin.x - 10, bounds.origin.y, bounds.size.width, bounds.size.height);
}

返回符合您需求的CGRect。

我没有看到这个,屏幕截图会有所帮助。 但是,快速回答是您可以检查UITextField的子视图数组,找到包含clear按钮的子视图,并调整其frame.origin。

编辑:似乎我已经为这个答案(2010年写的)投了反对票。 这不是一个“正式”批准的方法,因为你正在操纵私有对象,但Apple无法检测到它。 主要风险是视图层次结构可能在某些时候发生变化。

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

}

Swift 4版本将是

import UIKit

class LoginTextField: UITextField {

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

}

斯威夫特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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM