2010-10-07 96 views

回答

9

只需製作一個uibutton並將其放在uitextview上並將其操作設置爲明文視圖;

uitextview.frame = (0,0,320,416); 

uibutton.frame = (310,0,10,10); 
[uibutton setimage:@"cross.png" forcontrolstate:uicontrolstatenoraml]; 
[uibutton addTarget:self action:@selector(clearButtonSelected:) forControlEvents:UIControlEventTouchUpInside]; 

-(void)clearButtonSelected{ 
    [email protected]""; 
} 

希望要清除文本視圖文本當你點擊十字鍵的上方幫助 如果不明白的話,我可以給你適當的程序爲

+0

完美。謝謝。 – Abhinav 2010-10-07 15:56:01

+3

遇到同樣的需求,在哪裏得到這個cross.png? – tom 2011-12-27 19:56:50

1

沒有什麼內置的UITextField。你必須自己添加視圖(可能是一個UIButton)並將其正確放置,並以某種方式讓文本正確包裝。 (我認爲後者是不可能的。)

也許您應該在鍵盤上方顯示一個工具欄(如果您的目標是3.2或更高版本,則應該顯示一個inputAccessoryView),它提供了一個清除按鈕。

0

對我來說改變.frame或.contentInset屬性不起作用。

對我來說,最好的結果來自:

1)添加一個UIView控制器,給它圓潤的邊角和邊框來模擬一個UITextView。

self.viewTextBackground.layer.borderColor = [UIColor colorWithRed:171/255.0 green:171/255.0 blue:171/255.0 alpha:1.0].CGColor; 
self.viewTextBackground.layer.borderWidth = 1.0f; 
self.viewTextBackground.layer.cornerRadius = 9.0f; 

2)將UITextView放在這個UIView上面。放置它以便底層UIView的邊界保持可見。

3)給予的UITextView圓角:

self.textNote.layer.cornerRadius = 9.0f; 

3)使其寬度FE。與底層UIView相比,30像素更少。你現在有一個清除按鈕的空間。

4)只需將UIButton添加到您的控制器並將其放置在底層UIView的右上角。

5)更改按鈕屬性:將其類型設置爲「自定義」並將其圖像設置爲灰色十字圖像。

6)結合的操作與按鈕TE清除的UITextView

11

基於來自騎手的更精確和最新執行答案:

int kClearButtonWidth = 15; 
int kClearButtonHeight = kClearButtonWidth; 

//add the clear button 
self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
[self.clearButton setImage:[UIImage imageNamed:@"UITextFieldClearButton.png"] forState:UIControlStateNormal]; 
[self.clearButton setImage:[UIImage imageNamed:@"UITextFieldClearButtonPressed.png"] forState:UIControlStateHighlighted]; 

self.clearButton.frame = CGRectMake(0, 0, kClearButtonWidth, kClearButtonHeight); 
self.clearButton.center = CGPointMake(self.textView.frame.size.width - kClearButtonWidth , kClearButtonHeight); 

[self.clearButton addTarget:self action:@selector(clearTextView:) forControlEvents:UIControlEventTouchUpInside]; 

[self.textView addSubview:self.clearButton]; 

,並且該方法

- (void)clearTextView:(id)sender{ 
    self.textView.text = @""; 
} 

您可以將此圖像用於按鈕的兩種狀態:

UITextFieldButton UITextFieldButtonPressed

+0

一個完美的答案,但XCode 6堅持使用AutoLayout,我不得不放棄以編程方式創建按鈕,因爲您必須添加約束來確保它出現在正確的位置。最後,我直接在故事板上添加了一個UIButton,並在其中添加了約束。 (嘆息...) – 2015-01-05 08:55:11

5

從產品的角度來看,如果你將有一個明確的按鈕,你可能想使用UITextField代替UITextViewUITextField支持清除按鈕本身 - 的clearButtonMode屬性設置爲這樣:

UITextField *textfield = ...; 
textfield.clearButtonMode = UITextFieldViewModeAlways; 

見截圖:

enter image description here

當用戶主動更新內容時,您可以使用UITextFieldViewModeWhileEditing僅顯示清除按鈕。

+0

謝謝!正是我需要的。 – ninjudd 2014-12-04 05:03:06

+5

(嘆氣)問題是如何添加一個清除按鈕到UITextView(而不是UITextField)...並且沒有ClearButtonMode成員函數... !! – 2014-12-25 20:34:05

+0

@Mike Gledhill,剛剛更新瞭解決您的評論的答案,我認爲對於像清除「UITextView」這樣的內容,您最好使用清晰的按鈕(即「UIButton」)。我只是看不出X清除按鈕如何與多行文本視圖一起工作。 – Zorayr 2014-12-26 19:13:12