1

私はブロックが機能する方法が本当に好きで、のアクションを設定するようないくつかの場所にブロックを追加するといいと思いましたUIRefreshControl.

だから私はtoを作成しましcategoryUIRefreshControl

@interface UIRefreshControl (Blocks)

@property (nonatomic, copy) void (^actionBlock)();

- (id)initWitActionBlock:(void (^)())actionBlock;

@end

@implementation UIRefreshControl (Blocks)

- (id)initWitActionBlock: (void (^)())actionBlock {
    self = [super init];
    if (self) {
        self.actionBlock = [actionBlock copy];
        [self addTarget:self action:@selector(fireActionBlock) forControlEvents:UIControlEventValueChanged];
    }
    return self;
}

- (void)fireActionBlock {
        self.actionBlock();
}

@end

どちらがクラッシュしていますか:理由: '-[UIRefreshControl setActionBlock:]: 認識されないセレクターがインスタンスに送信されました

しかし、私はブロックについてあまり知りませんし、これcategorysubclass同じことをすることの違いもよくわかりません。

プロパティで何が起こっているのかを完全には理解していないと思うので、どうすればよいですか? また、可能であれば、これでよろしいですか?それとも、私はこれをやるべきではありませんか?

EDIT: * @Martin Rに関連する参照のおかげで解決策!

static char const * const ActionBlockKey = "ActionBlockKey";

@interface UIRefreshControl (Blocks)

@property (nonatomic, copy) void (^actionBlock)();

- (id)initWitActionBlock:(void (^)())actionBlock;

@end

@implementation UIRefreshControl (Blocks)
@dynamic actionBlock;

- (id)initWitActionBlock: (void (^)())actionBlock {
    self = [super init];
    if (self) {
        self.actionBlock = [actionBlock copy];
        [self addTarget:self action:@selector(fireActionBlock) forControlEvents:UIControlEventValueChanged];
    }
    return self;
}

- (void)fireActionBlock {
        self.actionBlock();
}

- (id)actionBlock{
    return objc_getAssociatedObject(self, ActionBlockKey);
}

- (void)setActionBlock:(void (^)())actionBlock{
    objc_setAssociatedObject(self, ActionBlockKey, actionBlock,  OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
4

3 に答える 3

0
    Try Class Extension. 

    File- New - Swift class - Create one.

    public extension UIRefreshControl
    {
        func makeRefreshView()
        {

            attributedTitle = NSAttributedString(string: "Refreshing ")
            backgroundColor = UIColor.clearColor()
            addTarget(self, action: "refreshnow", forControlEvents: UIControlEvents.ValueChanged)

        }
        func refreshnow()
        {
            print("refreshing and loading")
            endRefreshing()
        }
    }


    Implementation.

let refreshControl = UIRefreshControl()
refreshControl.makeRefreshView()
self.bidderlisttable.addSubview(refreshControl)
refreshControl.refreshnow()
于 2015-09-10T13:51:43.627 に答える