我想为 UIButton 子类创建一个组件。要设置按钮,我想设置图像。我的问题是我不知道如何制作一个 CKComponentViewAttribute ,它采用 UIButton 方法所需的两个参数setImage:forState:
。
我试过这个:
[CKComponent newWithView:{
[KGHitTestingButton class],
{
{CKComponentActionAttribute(@selector(onMenuTap))},
{@selector(setImage:forState:), [UIImage imageNamed:@"location_action"]}, @(UIControlStateNormal)},
}
} size:{.width = 30, .height = 30}]
但这不会编译。这个版本也一样:
{@selector(setImage:forState:), @[[UIImage imageNamed:@"location_action"]}, @(UIControlStateNormal)]},
}
我在这里读到http://componentkit.org/docs/advanced-views.html我需要将我的输入装箱到一个对象中。在这种情况下我该怎么做?
更新:我在这里找到了以下提示https://github.com/facebook/componentkit/issues/265:
“CKComponentViewAttribute 可以用任意块初始化。这是一个例子:
static const CKComponentViewAttribute titleShadowColorAttribute = {"MyComponent.titleShadowColor", ^(UIButton *button, id value){
[button setTitleShadowColor:value forState:UIControlStateNormal];
}};
"
这就是我最终设法解决问题的方法:
static const CKComponentViewAttribute imageAttribute = {"LocationActionButton.imageAttribute", ^(UIButton *button, id value){
[button setImage:value forState:UIControlStateNormal];
}};
CKComponent *locationActionButton = [CKComponent newWithView:{
[UIButton class],
{
{@selector(setBackgroundColor:), [UIColor redColor]},
{imageAttribute, [UIImage imageNamed:@"location_action"]}
}
} size:{.width = 30, .height = 30}];
您可以内联以使其更短:
CKComponent *locationActionButton = [CKComponent newWithView:{
[UIButton class],
{
{@selector(setBackgroundColor:), [UIColor redColor]},
{{"LocationActionButton.imageAttribute", ^(UIButton *button, id value){
[button setImage:value forState:UIControlStateNormal];
}}, [UIImage imageNamed:@"location_action"]}
}
} size:{.width = 30, .height = 30}];