制作 UIButton 复选框的最佳方法是什么? [英] What is the best way to make a UIButton checkbox?

查看:22
本文介绍了制作 UIButton 复选框的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从带有标题和图像的 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.

起初我尝试子类化 UIButtonUIButton 没有 -init*** 方法可用于我的 -init 方法.

At first I tried subclassing UIButton but UIButton has no -init*** method to use in my -init method.

最好的方法是什么?

提前致谢.

推荐答案

您不需要继承 UIButton 类.按照设计,Objective-C 更喜欢组合而不是继承.

You shouldn't need to subclass the UIButton class. By design, Objective-C favors composition over inheritance.

UIButtonUIControl 的子类,它有一个 selected 属性.您可以使用此属性来切换复选框的开/关行为,就像 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:checkedImage 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆