美文网首页iOS劝退指南
UIButton addTarget:self action:@

UIButton addTarget:self action:@

作者: MccReeee | 来源:发表于2017-03-03 13:36 被阅读944次

利用RunTime中的objc_setAssociatedObject函数可以轻松做到

/** 
 * Sets an associated value for a given object using a given key and association policy.
 * 
 * @param object The source object for the association.
 * @param key The key for the association.
 * @param value The value to associate with the key key for object. Pass nil to clear an existing association.
 * @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
 * 
 * @see objc_setAssociatedObject
 * @see objc_removeAssociatedObjects
 */
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);

以下是我项目中的代码
先将参数通过key绑定在btn上

TestMode1 *model1 = [[TestMode1 alloc]init];
TestMode2 *model2 = [[TestMode2 alloc]init];
objc_setAssociatedObject(self.popView.btnYES, "model1", model1, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(self.popView.btnYES, "model2", model2, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self.popView.btnYES addTarget:self action:@selector(changePeriod:) forControlEvents:UIControlEventTouchUpInside];

在点击事件函数中通过objc_getAssociatedObject将多个参数取出来即可

- (void)changePeriod:(UIButton *)btn{
    [self removeTheTipView];
    TestMode1 *m1 = objc_getAssociatedObject(btn, "model1");
    TestMode2 *m2 = objc_getAssociatedObject(btn, "model2");

}

当然要是通过声明一个全局变量来传值也是可以的

相关文章

网友评论

    本文标题:UIButton addTarget:self action:@

    本文链接:https://www.haomeiwen.com/subject/dpzlgttx.html