2014-10-19 44 views
3

我使用UIMenuItemUIMenuController亮點功能添加到我的UITextView,因此用戶可以更改所選文本的背景顏色,如圖片所示波紋管:UITextView的文本選擇和突出的iOS跳8

    UITextView
  • Setected文本與提供給用戶的亮點特點:

Setected text in <code>UITextView</code>

  • 突出顯示的文本中UITextView用新的背景顏色,在高亮特徵輕敲後由用戶選擇: Highlighted text in <code>UITextView</code> with a new background color

的iOS 7以下代碼工作完美地完成這項任務:

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)]; 
    [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]]; 
} 

- (void)highlight { 

    NSRange selectedTextRange = self.textView.selectedRange; 

    [attributedString addAttribute:NSBackgroundColorAttributeName 
          value:[UIColor redColor] 
          range:selectedTextRange]; 

    // iOS 7 fix, NOT working in iOS 8 
    self.textView.scrollEnabled = NO; 
    self.textView.attributedText = attributedString; 
    self.textView.scrollEnabled = YES; 
} 

但在iOS 8文本選擇正在跳躍。當我使用來自UIMenuItemUIMenuController突出顯示功能時,它也會跳轉到另一個UITextView偏移量。

我該如何解決這個問題iOS 8

回答

7

我最終解決我的問題是這樣的,如果別人有一個更優雅的解決方案,請讓我知道:

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)]; 
    [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]]; 

    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue]; 

    if (sysVer >= 8.0) { 
     self.textView.layoutManager.allowsNonContiguousLayout = NO; 
    } 
} 

- (void)highlight { 

    NSRange selectedTextRange = self.textView.selectedRange; 

    [attributedString addAttribute:NSBackgroundColorAttributeName 
          value:[UIColor redColor] 
          range:selectedTextRange]; 

    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue]; 
    if (sysVer < 8.0) { 
     // iOS 7 fix 
     self.textView.scrollEnabled = NO; 
     self.textView.attributedText = attributedString; 
     self.textView.scrollEnabled = YES; 
    } else { 
     self.textView.attributedText = attributedString; 
    } 
} 
+0

非常感謝你!我試圖解決這個問題:textView.scrollEnabled = false ... textView.scrollEnabled = true,但在ios 8中不起作用。剛剛添加self.textView.layoutManager.allowsNonContiguousLayout = false並且一切正常 – schirrmacher 2014-11-23 18:33:23

+0

好極了。我很高興能夠提供幫助。 – Winston 2014-11-24 01:46:03

+0

在我的應用程序中,禁用scrollEnabled仍然阻止了iOS 8中的跳轉,但是任何嘗試重新啓用它都沒有影響,因此在第一次編輯後滾動變爲永久禁用。禁用allowedNonContiguousLayout可以避免這個問題。我不知道這樣做是否有缺點,所以爲了以防萬一,編輯後我重新啓用了它。 – arlomedia 2015-03-12 21:33:40

0

move self.textView.scrollEnabled = NO;到第一行的高亮方法。

希望它有幫助!

+0

謝謝您的回答ZAZ,但沒有奏效。我仍然有同樣的問題。 – Winston 2014-10-19 19:08:17

+0

它滾動到另一個位置還是回到其原始位置?如果你可以不用評論這個'self.textView.attributedText = attributedString;'然後檢查響應。我知道這樣做不會突出顯示文字。 – ZAZ 2014-10-19 19:21:45

+0

我試過你的建議,它是否滾動到另一個位置,更具體地說是UITextView的開始。如果我在文本的開頭選擇並突出顯示,它將不再滾動。 – Winston 2014-10-19 19:46:53

相關問題