可以将UIBarButtonItem添加到分段控件中

问题描述

|| 我想知道是否可以将UIBarButtons添加到SegmentedControl。它可以编译,但会给出运行时错误
-[UIBarButtonItem isEqualToString:]: unrecognized selector sent to instance 0x4b4fcc0
这是我的代码
UIBarButtonItem *atolButton = [[UIBarButtonItem alloc] initWithTitle:@\"A to L\"
      style:UIBarButtonItemStyleBordered target:self action:@selector(atol:)];

UIBarButtonItem *ltozButton = [[UIBarButtonItem alloc] initWithTitle:@\"L to Z\"
      style:UIBarButtonItemStyleBordered target:self action:@selector(ltoz:)];

NSArray *titleButtons = [NSArray arrayWithObjects: atolButton,ltozButton,nil];

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:titleButtons];
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
...

- (void)atol:(id) sender {
NSLog(@\"atol called\");  
}

- (void)ltoz:(id) sender {
    NSLog(@\"ltoz called\");
}
我已经能够使其与以下代码一起使用
NSArray *itemArray = [NSArray arrayWithObjects: @\"a to l\",@\"l to z\",nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
segmentedControl.selectedSegmentIndex = 1;
[segmentedControl addTarget:self action:@selector(atol:)
     forControlEvents:UIControlEventValueChanged];

self.navigationItem.titleView = segmentedControl;

[segmentedControl release];
    

解决方法

        
UISegmentedControl
继承自
UIControl
,而
UIControl
继承自
UIView
,因此可以像向UIView一样向其添加subViews。 但是,分段方面是完全不同的。每个段都有一个
image
属性和
title
属性,仅此而已。 当您调用
initWithItems:
时,它必须是
UIImages
NSStrings
NSArray
。 我不知道您要做什么,迫使您将按钮添加到分段控制器中,但是我建议您改为设置
UISegmentedController
title
image
属性,并使用控制器要使用的任何方法自定义操作引起。例如:
-(void)segmentAction:(UISegmentedController *)segment {
    if (segment.selectedSegmentIndex == 0) {
        [self atol];
    } else {
        [self ltoz];
    }
}
我不知道您无法以这种方式完成自己想做的事情。