2013-06-29 92 views
1

我想在UITextView中禁用文本編輯,只有光標應該保留。我已經禁用了鍵盤,剪切複製粘貼菜單和縮放編輯模式。但是仍然存在一個問題 - 如果我在TextView上雙擊會選擇整個單詞。還有一件事,我該如何讓光標選擇任何地方,而不僅僅是詞的結尾或開始?在UITextView中禁用文本選擇

我做了屏幕截圖,它更好地描述了我的問題,但由於聲譽而無法發佈。所以我希望你能明白我的意思。

子類的UITextView的:

#import "UIUneditableTextView.h" 

@implementation UIUneditableTextView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender 
{ 
    UIMenuController *menuController = [UIMenuController sharedMenuController]; 
    if (menuController) { 
     [UIMenuController sharedMenuController].menuVisible = NO; 
    } 
    return NO; 
} 

-(void)addGestureRecognizerForLongPress:(UIGestureRecognizer *)gestureRecognizer 
{ 
    if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]){ 
     gestureRecognizer.enabled = NO; 
    } 
    [super addGestureRecognizer:gestureRecognizer]; 
    return; 
} 

@end 

回答

1

這裏談到斯威夫特工作示例

class TextView: UITextView { 

    override func canPerformAction(action: Selector, withSender sender: AnyObject!) -> Bool { 
     return false 
    } 

    override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer!) -> Bool { 
     if gestureRecognizer.isKindOfClass(UITapGestureRecognizer) && ((gestureRecognizer as UITapGestureRecognizer).numberOfTapsRequired == 1) { 
      let touchPoint = gestureRecognizer.locationOfTouch(0, inView: self) 
      let cursorPosition = closestPositionToPoint(touchPoint) 
      selectedTextRange = textRangeFromPosition(cursorPosition, toPosition: cursorPosition) 
      return true 
     } 
     else { 
      return false 
     } 
    } 

} 
2

中只看UITextInput因爲這樣的方法就是選擇控制。您可以像inputDelegate那樣找出何時selectionWillChange:並覆蓋selectedTextRange來控制選擇和脫字符。

文檔:http://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html#//apple_ref/occ/intfp/UITextInput

+1

你是什麼意思與「你可以作爲'inputDelegate'行動」?我很確定你不能。根據Apple文檔:「UIKit提供了一個私人文本輸入委託,它在運行時將其分配給其採用UITextInput協議的對象的'inputDelegate'屬性。」 –

3

既然你已經超載文本視圖,實現gestureRecognizerShouldBegin:我不喜歡這樣的實現。

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { 
    // Check for gestures to prevent 
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) { 
     // Check for double tap 
     if (((UITapGestureRecognizer *)gestureRecognizer).numberOfTapsRequired == 2) { 
      // Prevent the double tap 
      return NO; 
     } 
    } 

    // Always anything that makes it here 
    return YES; 
} 

你可能想考慮在這裏檢查長手勢識別器,這是少得多的黑客。