把UISegmentedControl放在一个UISearchBar中

本文关键字:一个 UISearchBar UISegmentedControl | 更新日期: 2023-09-27 18:14:00

我使用内置的搜索范围与UISearchDisplayController,我只有2段。

问题是,我们的设计需要按钮更小,居中(这在iPad上看起来尤其糟糕,因为按钮被拉伸得非常宽)。

是否有一种方法可以使UISegmentedControl居中并使其变小?我已经通过循环subViews得到了UISegmentedControl。我可以用setWidth:forSegmentAtIndex设置每个段的宽度,但是控件停靠在左边。我怎么居中呢?

PS -我的应用程序是MonoTouch (Xamarin.iOS),但Obj-C答案是受欢迎的。

把UISegmentedControl放在一个UISearchBar中

您是通过IB还是通过编程添加此内容?在IB中,我不得不关闭"自动调整子视图大小",并通过代码动态地调整控件的大小。我把需要调整大小的控件放到一个视图中,我可以绑定到这个视图,然后把我的控件放在那个视图的中心。这里有一个例子。我有两个按钮并排放在横向模式下,但它应该给你一个概念。

// get the current sizes of the things we are moving
CGRect saveRect = self.viewButtons.frame;  // the enclosing view
CGRect addLocRect = self.buttonAddLocation.frame;  // button 1
CGRect connectRect = self.buttonConnect.frame;     // button 2
// This will be set below in one of the if-else branches
CGFloat buttonWidth = 0;
// determine the offset from the left/right based on device and orientation
int offsetLeft = 0;
int offsetRight = 0;
if ([self isIphone]) {
    offsetLeft = (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) ? OFFSET_LEFT_PORTRAIT_IPHONE : OFFSET_LEFT_LANDSCAPE_IPHONE;
    offsetRight = (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) ? OFFSET_RIGHT_PORTRAIT_IPHONE : OFFSET_RIGHT_LANDSCAPE_IPHONE;
} else {
    offsetLeft = (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) ? OFFSET_LEFT_PORTRAIT_IPAD : OFFSET_LEFT_LANDSCAPE_IPAD;
    offsetRight = offsetLeft;
}

// change the size & location of the buttons to maximize the area for the location list
// no matter what orientation, the button frame will fill the bottom of the screen
saveRect.size.width = _windowWidth -offsetLeft - offsetRight;
// for Landscape, move the buttons to side-by-side at the bottom of the window
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
    // size & move the buttons to fit side-by-side
    buttonWidth = (saveRect.size.width)*.4;
    // addLocRect.origin.x += offset;
    addLocRect.origin.y = saveRect.size.height - addLocRect.size.height ;
    connectRect.origin.x = saveRect.size.width - buttonWidth - offsetRight;
    connectRect.origin.y = saveRect.size.height - connectRect.size.height;
} else { // Portrait
    // move the buttons down to the bottom of the frame, stacked
    // size the buttons to be fully across the screen
    buttonWidth = saveRect.size.width-2*offsetLeft;
    addLocRect.origin.y = 0 ; // at the top of the button view
    addLocRect.origin.x = offsetLeft;
    connectRect.origin.y = saveRect.size.height - connectRect.size.height;
    connectRect.origin.x = offsetLeft;
}
connectRect.size.width = buttonWidth;
addLocRect.size.width = buttonWidth;
self.buttonAddLocation.frame = addLocRect;
self.buttonConnect.frame = connectRect;