2012-03-28 82 views

回答

21

你應該創建你自己的UIButton(帶圖像,你需要一個你想要的png按鈕),將它實例化並將這個按鈕放在你的UITextField的右側視圖中。

CGFloat myWidth = 26.0f; 
CGFloat myHeight = 30.0f; 
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)]; 
[myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateNormal]; 
[myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateHighlighted]; 

[myButton addTarget:self action:@selector(doClear:) forControlEvents:UIControlEventTouchUpInside]; 

myTextField.rightView = myButton; 
myTextField.rightViewMode = UITextFieldViewModeUnlessEditing; 

你可能需要改進使用比對(這些是示例值):

myButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0); 

然後,你將需要實現方法 - (無效)doClear(ID)發送;這將清除您的文本框。

+0

非常感謝!我會嘗試它! – sergiocg90 2012-03-28 20:38:40

+1

如果您需要顯示「編輯時」按鈕,則需要將'rightViewMode'更改爲'UITextFieldViewModeWhileEditing' – 2012-03-28 20:40:36

+1

我製作了一個可用的示例清除按鈕。 https://www.chillysky.com/apps/Clear.png – 2013-08-12 04:58:26