尝试移动我的自定义 UITextField 清除按钮,但它不会正确调整大小或移动

Posted

技术标签:

【中文标题】尝试移动我的自定义 UITextField 清除按钮,但它不会正确调整大小或移动【英文标题】:Trying to move my custom UITextField clear button but it won't size or move correctly 【发布时间】:2014-08-04 23:21:39 【问题描述】:

所以我有一个用于我的通用 UITextField 的自定义 clearButton。我正在尝试移动 clearButton,因为我的 uitextfield 的背景在右侧有一些设计内容。我需要将清除按钮推到大约 150 像素以上。

我尝试了所有这些组合,但最终将清除按钮推离屏幕或使清除按钮非常宽,因此 uitextfield 中的文本停止变短。

第一次尝试

UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];

CGRect rect;
UIEdgeInsets contentInsets;
CGRect result;
[clearBtn setImage:[UIImage imageNamed:@"design.png"] forState:UIControlStateNormal];
rect = CGRectMake(0, 0, 45, 45);
contentInsets = UIEdgeInsetsMake(0, 50, 0, 0);
result = UIEdgeInsetsInsetRect(rect, contentInsets);
[clearBtn setFrame:result];

第二次尝试

UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];

CGRect rect;
UIEdgeInsets contentInsets;
CGRect result;
[clearBtn setImage:[UIImage imageNamed:@"design.png"] forState:UIControlStateNormal];
rect = CGRectMake(0, 0, 45, 45);
contentInsets = UIEdgeInsetsMake(0, 250, 0, 150);
result = UIEdgeInsetsInsetRect(rect, contentInsets);
[clearBtn setFrame:result];

【问题讨论】:

【参考方案1】:

更好的选择是继承 UITextField 并覆盖 clearButtonRectForBounds: 方法。

- (CGRect)clearButtonRectForBounds:(CGRect)bounds 
    CGRect rect = [super clearButtonRectForBounds:bounds];
    rect.origin.x -= 150;

    return rect;

这会将清除按钮从其正常位置向左移动 150 点。

【讨论】:

以上是关于尝试移动我的自定义 UITextField 清除按钮,但它不会正确调整大小或移动的主要内容,如果未能解决你的问题,请参考以下文章

您可以在自己的自定义控件中重用 UITextField 中的“清除”按钮图形(其中带有“x”的圆圈)吗?

如何在Swift 3中修复我的自定义UITextField对象?

iOS:删除 UITextField 的默认绘图

UITextField 清除按钮与屏幕动画一起使用

自定义表格单元格的uitextfield

识别按下的标签按钮以移动到下一个响应者