制作自定义UISegmentedControl(排序)

时间:2011-04-02 02:15:29

标签: iphone objective-c uiview menu custom-controls

我有这个模拟:

enter image description here

正如您所看到的,它是一种导航菜单。它的功能应该与分段控件相同,我将根据活动项更改tableView。

实现此目的最简单的方法是什么?

我已经开始使用我的UIView-subclass,但发现我必须做一个代表,注意tap事件和东西。 这是最好的方式吗我应该继承UISegmentedControl吗?

还有其他建议吗?

请指出正确的方向。我对Obj-c充满信心,但制作这些东西让我的思绪变得疯狂。

1 个答案:

答案 0 :(得分:4)

从概念上讲,UISegmentedControl似乎是一个不错的选择,但我认为它不够灵活,无法创造你想要的效果。

您是否考虑在自定义视图中放置三个UIButton控件?您可以使用setBackgroundImage:forState:自定义每个按钮的图像,以获取模型中的边框样式。将按下的按钮的selected属性设置为YESUIButton将为您处理绘图。

您可以设置一个操作方法,通过调用

来检测按下了哪个按钮
[button addTarget:self action:@selector(nameOfMethodToHandleButtonPress) forControlEvents:UIControlEventTouchUpInside])]

委托只是符合您创建的协议的任何类。因此,您可以在标题中创建一个委托协议,如下所示:

@class MyControl; // this is a forward reference to your class, as this must come before the class @interface definition in the header file

@protocol MyControlDelegate <NSObject>

@optional
- (void)myControl:(MyControl *)control didSelectButton:(int)buttonIndex; // replace this method with whatever makes sense for your control

@end

代表只是MyControl课程中的一个属性:

@property (nonatomic, assign) id <MyControlDelegate> delegate; // you use 'assign' instead of 'retain' to prevent retain cycles

在您的按钮按下处理程序,例如:

- (void)methodThatHandlesButtonPress { // this is the method you set up in the first code example with addTarget:action:forCotnrolEvents:
    if ([self.delegate respondsToSelector:@selector(myControl:didSelectButton:)])
        [self.delegate myControl:self didSelectButton:0]; // replace as appropriate
}

现在,您只需让包含控件的视图控制器采用协议:

@interface MyViewController : UIViewController <MyControlDelegate> { // etc...

并实施方法:

- (void)myControl:(MyControl *)control didSelectButton:(int)buttonIndex {
    // handle the button press as appropriate
}