除了 DexterW 的回答。我做出了同样的决定——只模仿UISegmentedControl
使用UIButtons
。
然而,模仿它并不是一项简单的任务UISegmentControl
。我尝试使用Selected
a 的状态,UIButton
但如果为和状态UIButton
设置相同的设置(背景图像、字体颜色),则不会按预期工作。在这种情况下,当片段看起来被选中时,它在视觉上仍然是“可按压的”。因此,为了避免它并使按钮设置的行为更像我根本没有使用状态。相反,Id 决定在代码中更改选定按钮的外观,以便选定按钮的状态在视觉上是相同的,而对于未选定的按钮则不同。Hightlighted
Selected
UISegmentedControl
selected
normal
highlighted
假设我有3个按钮segmentedControl(LeftSgm | MiddleSgm | RightSgm),对于正常状态,我使用名为“segment_default”的背景图片和白色字体,对于选定状态,它的背景图片名为“segment_active”和黑色字体。所以在 onTouchDown 中:
-(IBAction)onTopMenuTap:(id)sender
{
int newSelectedSegmentIndex;
if (sender == btnLeftSgm)
newSelectedSegmentIndex=0;
else if (sender == btnMiddleSgm)
newSelectedSegmentIndex=1;
else if (sender == btnRightSgm)
newSelectedSegmentIndex=2;
else
return;
NSLog(@"Tapped segment index %d while old one is %d",newSelectedSegmentIndex,selectedSegmentIndex);
if (newSelectedSegmentIndex==selectedSegmentIndex)
return;
[self handleSegmentAppearenace:newSelectedSegmentIndex];
//do whatever its need to be done
...
}
并且被调用的方法是
-(void)handleSegmentAppearenace:(int)newSelectedSegmentIndex
{
if (selectedSegmentIndex==0){
[btnLeftSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_default_left"] forState:UIControlStateNormal];
[btnLeftSgm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnLeftSgm.highlighted = NO;
}
else if (selectedSegmentIndex==1){
[btnMiddleSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_default_center"] forState:UIControlStateNormal];
[btnMiddleSgm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnMiddleSgm.highlighted = NO;
}
else if (selectedSegmentIndex==2){
[btnRightSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_default_right"] forState:UIControlStateNormal];
[btnRightSgm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
btnRightSgm.highlighted = NO;
}
if (newSelectedSegmentIndex==0){
[btnLeftSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_active_left"] forState:UIControlStateNormal];
[btnLeftSgm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btnLeftSgm.highlighted = YES;
}
else if (newSelectedSegmentIndex==1){
[btnMiddleSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_active_center"] forState:UIControlStateNormal];
[btnMiddleSgm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btnMiddleSgm.highlighted = YES;
}
else if (newSelectedSegmentIndex==2){
[btnRightSgm setBackgroundImage:[UIImage imageNamed:@"segmented_control_active_right"] forState:UIControlStateNormal];
[btnRightSgm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btnRightSgm.highlighted = YES;
}
}
所有三个按钮都在 IB 中绑定到相应的属性(btnRightSgm 等)。也为“修饰事件” onTopMenuTap 绑定。
不能说这是一个最好的主意,但它对我来说非常有效。