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

时间:2014-08-04 23:21:40

标签: ios objective-c uitextfield uiedgeinsets

所以我有一个自定义的clearButton用于我的通用UITextField。我试图移动clearButton作为我的uitextfield的背景在右侧有一些设计的东西。我需要将清除按钮推过大约150个像素。

我尝试了所有这些组合,但它最终将clearbutton推离屏幕或使清除按钮非常宽,以便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 个答案:

答案 0 :(得分:3)

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

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

    return rect;
}

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