Creating a custom slider using Sprite Kit - how do I pass a @selector?

别等时光非礼了梦想. 提交于 2019-12-05 19:23:16

Just implement the missing method in your custom slider. Add this in the interface:

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

And in implementation store target and action as a properties.

@property (nonatomic, strong) id target;
@property (nonatomic) SEL action;

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    _target = target;
    _action = action;
}

Then call an action on a target when value changes:

objc_msgSend(_target, _action);

Remember to import:

#import <objc/message.h>

Then to get the updates from the slider create a valueChanged method and add it:

- (void)valueChanged
{
    CGFloat value = _yourSlider.value;
    // Do something with the value.
}

[_yourSlider addTarget:self action:@selector(valueChanged) forControlEvents: UIControlEventValueChanged];

The variable type for a selector is SEL. Here's how you would declare properties to keep track of the target and action. (Note that SEL is a pointer to a structure, not a pointer to an object, so specifying strong or weak will upset the compiler.)

@property (nonatomic, strong) id target;
@property (nonatomic) SEL action;

Here's a sample method that updates the target and action

- (void)changeTarget:(id)target action:(SEL)action
{
    self.target = target;
    self.action = action;
}

And this is how you call the action method on the target

[self.target performSelector:self.action withObject:self afterDelay:0.0];

Note that self is passed as an argument to the method, so the method signature in the target should be

- (void)someAction:(id)sender
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!