如何用swift制作单选按钮?

How to make radio button with swift?

我尝试了很多代码,但没有一个对我有用。当我向用户显示问题以选择其中一个单选按钮时,我需要用 swift 制作四个单选按钮。

遗憾的是,Swift 没有内置的方法来执行此操作,但很容易编写代码。我个人推荐使用这个 Git project,因为我听说过它的好消息。

如果您想从头开始构建单选按钮,我建议您使用带有 UIControlStateSelected 触发检查 img 的常规按钮来制作检查按钮,然后设置 layer.cornerRadius(当然是在设置 clipsToBounds = true 之后)将按钮的宽度减半以生成一个圆圈!

您可以使用带有按钮标记的可变字典作为字典的键来创建自己的登录名。为所选按钮添加 green/selected 图像并为所选按钮的字典中的键(按钮标签)设置 "yes" 值,为其他按钮的标签设置 "no" 值。

我有一个 example 相同但在 Objective -C

在swift iOS中提供最接近单选按钮行为的UIControl是UISegmentedControl,看看reference

这里是apple's guidelines for mobile controls

这篇文章的一些引用:

Use a segmented control to offer choices that are closely related but mutually exclusive.

A segmented control:

  • Consists of two or more segments whose widths are proportional, based on the total number of segments
  • Can display text or images