在ios 11中未触发事件UIControlEventValueChanged的UISegmentedControl选择器

时间:2017-10-10 11:29:32

标签: ios objective-c selector uisegmentedcontrol ios11

我有一个UIToolbar,并为其添加了少量UISegmentedControl。我的问题是我的selector UISegmentedControl未在ios 11中调用。但它在IOS 10及更低版本中运行正常。

我有UITextField我有一个日期选择器作为输入视图,我已将此工具栏添加为assesory视图。当我单击工具栏中的完成按钮时,我设置了UITextField的值。

        UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
        [toolBar setBackgroundColor:[UIColor whiteColor]];

        doneButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:"done"  ]];
        doneButton.momentary = YES;
        doneButton.frame =CGRectMake(toolBar.frame.size.width - 50,5 , 30, toolBar.frame.size.height- 2 *5);
        [doneButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
        doneButton.tintColor = [UIColor blackColor];
        [doneButton addTarget:self action:@selector(donePressed) forControlEvents:UIControlEventValueChanged];
        [toolBar addSubview:doneButton];

在ios 11.0中永远不会调用donePressed方法,但相同的代码在较低的ios版本中工作正常。

请建议任何修复。

1 个答案:

答案 0 :(得分:0)

我按照以下方式尝试了您的代码,并使用iOS 11.1进行了工作。在SegmentControl的值更改事件

时正确调用选择器操作donePressed
//  ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

  @property IBOutlet UISegmentedControl * doneButton;

@end


//  ViewController.m

#import "ViewController.h"
@interface ViewController () {

}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupToolbar];
}


-(void)setupToolbar {
    self.doneButton.momentary = YES;
    [self.doneButton addTarget:self action:@selector(donePressed:) forControlEvents:UIControlEventValueChanged];
}

-(void)donePressed:(UISegmentedControl *)segmentControl {
    NSLog(@"segmentControl index - %ld",segmentControl.selectedSegmentIndex);
}
@end


故事板 - 查看控制器界面&amp; IBOutlet连接:

enter image description here


这是另一种解决方案 - 如何使用工具栏以编程方式处理选择器。希望这对你有用。

-(void)setupToolbar{
    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.frame = CGRectMake(0, 100, self.view.frame.size.width, 44);


    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)];
    item1.tag = 1;

    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donePressed:)];
    item2.tag = 2;

    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObjectsFromArray:@[item1, flexibleItem, item2]];
    [toolbar setItems:items animated:NO];
    [self.view addSubview:toolbar];

}

-(void)donePressed:(UIBarButtonItem *)barButtonItem {
    NSLog(@"barButtonItem tag - %ld",barButtonItem.tag);
}