【发布时间】:2011-02-25 10:13:58
【问题描述】:
由于某种原因,当我将 UITextfield 添加为表格单元格的内容视图的子视图时,清除按钮与在字段中键入的文本不对齐,并且出现在其下方。有什么办法可以移动 clearbutton 的文本来阻止这种情况发生?感谢您的帮助,
【问题讨论】:
标签: iphone objective-c uitableview uitextfield
由于某种原因,当我将 UITextfield 添加为表格单元格的内容视图的子视图时,清除按钮与在字段中键入的文本不对齐,并且出现在其下方。有什么办法可以移动 clearbutton 的文本来阻止这种情况发生?感谢您的帮助,
【问题讨论】:
标签: iphone objective-c uitableview uitextfield
正如@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
}
苹果docs 状态:
讨论你不应该直接调用这个方法。如果你想 将清除按钮放在不同的位置,您可以覆盖它 方法并返回新的矩形。你的方法应该调用 super 实现并仅修改返回的矩形的原点。 更改清除按钮的大小可能会导致不必要的失真 按钮图像。
【讨论】:
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)
}
}
【讨论】:
我继承了UITextField 并覆盖了函数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 的子视图数组,找到包含清除按钮的子视图,并调整其 frame.origin。
编辑:我似乎对这个答案(写于 2010 年)投了反对票。这不是“官方”批准的方法,因为您正在操作私有对象,但 Apple 无法检测到它。主要风险是视图层次结构可能会在某些时候发生更改。
【讨论】:
继承 UITextField 并覆盖此方法:
- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
return CGRectMake(bounds.origin.x - 10, bounds.origin.y, bounds.size.width, bounds.size.height);
}
返回符合您需求的 CGRect。
【讨论】:
斯威夫特 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)
}
}
【讨论】:
Swift 4 版本将是
import UIKit
class LoginTextField: UITextField {
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: xPos, y:yPos, width: yourWidth, height: yourHeight)
}
}
【讨论】: