【问题标题】:How to pragmatically connect signal to slot within ios?如何务实地将信号连接到ios中的插槽?
【发布时间】:2015-12-05 07:16:11
【问题描述】:

我在自定义UIView 中创建了一个段控件,现在如果段控件发生更改,我需要更改UIView's 颜色。

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.circleColor = [UIColor lightGrayColor];
        self.segmentControl = [[UISegmentedControl alloc] initWithItems: @[@"Red", @"Green", @"Blue"]];
        CGRect f = self.segmentControl.frame;
        f.origin = CGPointMake(0, [UIApplication sharedApplication].statusBarFrame.size.height);
        self.segmentControl.frame = f;
        [self addSubview:self.segmentControl];
    }
    return self;
}

我认为有类似self.segmentControl setCallbackForEvent:(UIEvent*)event:(Callback)action 的东西,但我无法在UIView 中找到这样的方法。

所以我尝试了以下代码,但也不行:

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    NSSet<UITouch*>* segTouches = [event touchesForView:self.segmentControl];
    if (segTouches.count != 0 && self.segmentControl.selected) {
        UIColor* color = nil;
        switch (self.segmentControl.selectedSegmentIndex) {
            case 0:
                color = [UIColor redColor];
                break;
            case 1:
                color = [UIColor greenColor];
                break;
            case 2:
                color = [UIColor blueColor];
                break;
            default:
                assert(0);
                break;

        }
        self.circleColor = color;
    }
}

如果没有 ios 中的界面生成器,我如何以编程方式将信号(段控制值更改)连接到插槽(更改为视图颜色)?

【问题讨论】:

    标签: ios objective-c xcode uiview


    【解决方案1】:

    来自关于分段控件的 Apple Docs

    您使用 UIControlEventValueChanged 常量为分段控件注册目标操作方法,如下所示。

    [segmentedControl addTarget:self
                     action:@selector(changeColor:)
           forControlEvents:UIControlEventValueChanged];
    

    然后您可以创建一个 changeColor: 函数并将颜色更改代码放入其中。

    【讨论】:

      【解决方案2】:

      您可以在doc 上了解如何使用UISegmentedControl。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多