2012-09-06 26 views
6

有沒有人試過用UISearchDisplayController和UISearchBar,它是UIToolbar中的UIBarButtonItem?iOS - 將UISearchDisplayController與UISearchBar一起使用,它是UIToolbar中的UIBarButtonItem

我將不勝感激如何成功做到這一點。

但是目前無論何時搜索控制器彈出它重繪的UISearchBar,我艱難地維持着相似的外觀到UIToolbar

+0

因此..你想自定義UISearchBar嗎?這是個問題嗎? –

+0

我想我有兩個問題: 1.如果我連接UISearchDisplayController,是否應該將UISearchBar嵌入到UIToolbar中? 2.如果UISearchDisplayController中的UISearchBar的外觀可以在激活這個過程時得到修復?目前它被重新繪製和重新定位,並且不保留UIToolbar中UISearchBar的外觀 – Rammeln

回答

5

通常你不會想要把一個搜索欄工具欄裏面,它似乎你想做一些類似於我所做的事情。

因此,這裏是我是如何做到的,它可以被稱爲黑客,但它就像一個魅力:)

首先,你必須將它設置在Interface Builder是這樣的:

enter image description here

請注意,搜索不是工具欄的子項,而是位於上方。

搜索欄應該有「清晰的顏色」背景和靈活的左,右和寬度自動調整掩碼。

您在工具欄下面放置一個黑色背景的1像素標籤,即。 [x = 0,y = 44,width = 320或frame width,height = 1],也是靈活的左,右和寬度自動調整掩碼。這是爲了在搜索顯示控制器顯示錶格後隱藏您獲得的一個可見像素視圖。嘗試一下沒有理解我的意思。

您設置了任何工具欄項目,並確保有他們的網點,因爲您將需要這些。

,現在的代碼...

當你開始搜索

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller 
{ 
    // animate the search bar to the left ie. x=0 
    [UIView animateWithDuration:0.25f animations:^{ 
     CGRect frame = controller.searchBar.frame; 
     frame.origin.x = 0; 
     controller.searchBar.frame = frame; 
    }]; 
    // remove all toolbar items 
    [self.toolbar setItems:nil animated:YES]; 
} 

當您結束搜索

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller 
{ 
    // animate search bar back to its previous position and size 
    // in my case it was x=55, y=1 
    // and reduce its width by the amount moved, again 55px 
    [UIView animateWithDuration:0.25f 
          delay:0.0f 
         // the UIViewAnimationOptionLayoutSubviews is IMPORTANT, 
         // otherwise you get no animation 
         // but some kind of snap-back movement 
         options:UIViewAnimationOptionLayoutSubviews 
        animations:^{ 
         CGRect frame = self.toolbar.frame; 
         frame.origin.y = 1; 
         frame.origin.x = 55; 
         frame.size.width -= 55; 
         controller.searchBar.frame = frame; 
        } 
        completion:^(BOOL finished){ 
         // when finished, insert any tool bar items you had 
         [self.toolbar setItems:[NSArray arrayWithObject:self.currentLocationButton] animated:YES]; 
        }]; 
} 

有了這個,我得到了一個漂亮的動畫如下: )

enter image description here

enter image description here

相關問題