什么是最好的方法来做一个UIButton复选框? [英] What is the best way to make a UIButton checkbox?
问题描述
我想从 UIButton
为我的iPhone应用程式建立标准复选框,标题和图片。
I am trying to make a standard check box for my iPhone app from a UIButton
with a title and image. The button image changes between an "unchecked" image and a "checked" image.
开始时我尝试子类化 UIButton
但是 UIButton
没有 -init ***
方法用于 -init
方法。
At first I tried subclassing UIButton
but UIButton
has no -init***
method to use in my -init
method.
这是最好的方法是什么?
What is the best way to do this?
。
推荐答案
您不应该需要继承 UIButton
类。根据设计,Objective-C优先于继承。
You shouldn't need to subclass the UIButton
class. By design, Objective-C favors composition over inheritance.
UIButton
是 UIControl
,它有一个选择的
属性。您可以使用此属性来切换复选框的打开/关闭行为,与 UISwitch
相同。
UIButton
is a subclass of UIControl
, which has a selected
property. You can use this property to toggle the on/off behaviour of a checkbox, just the same way a UISwitch
does.
您可以将一个操作附加到按钮的内部触发事件,并执行切换在那里,像这样:
You can attach an action to the button's touched up inside event, and perform the toggling in there, something like this:
// when you setup your button, set an image for the selected and normal states
[myCheckBoxButton setImage:nonCheckedImage forState:UIControlStateSelected];
[myCheckBoxButton setImage:nonCheckedImage forState:UIControlStateNormal];
- (void)myCheckboxToggle:(id)sender
{
myCheckboxButton.selected = !myCheckboxButton.selected; // toggle the selected property, just a simple BOOL
}
这篇关于什么是最好的方法来做一个UIButton复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!