Swift:以编程方式更改我的 UISegmentedControl 的项目
Swift: Programmatically changing my UISegmentedControl's Items
我想根据另一个选择更改我的 UISegmentedControl 中的项目。我不想更改项目的数量,而只是更改项目标签,以及 UISegmentedControl 的 'hidden' 变量。
这是我获取 UISegmentedControl 的代码:
@IBOutlet weak var viewPicker: UISegmentedControl!
这是更改它的代码:
viewPicker = UISegmentedControl(items: ["Description", "Location"])
但是,这不起作用,有时会将 viewPicker 设置为 nil,从而报错。最好的方法是什么?
UISegmentControl 有一个方法可以让您单独更改标签:
setTitle(_:forSegmentAtIndex:)
。所以你只需像这样在你的分段控件上使用它:
self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)
由于您将变量声明为 "weak",它会在您分配后立即被释放。但是无论如何你都不应该这样做,因为它是@IBOutlet -> 你应该通过接口构建器连接它。
至于更改标题,而不是仅仅创建新的 SC,使用
self.viewPicker.setTitle("", forSegmentAtIndex: index)
并隐藏/显示分段控件,
self.viewPicker.hidden = true / false
希望对您有所帮助!
对于 Swift 3.0 使用:
self.viewPicker.setTitle("Description", forSegmentAt: 0)
self.viewPicker.setTitle("Location", forSegmentAt: 1)
我想根据另一个选择更改我的 UISegmentedControl 中的项目。我不想更改项目的数量,而只是更改项目标签,以及 UISegmentedControl 的 'hidden' 变量。
这是我获取 UISegmentedControl 的代码:
@IBOutlet weak var viewPicker: UISegmentedControl!
这是更改它的代码:
viewPicker = UISegmentedControl(items: ["Description", "Location"])
但是,这不起作用,有时会将 viewPicker 设置为 nil,从而报错。最好的方法是什么?
UISegmentControl 有一个方法可以让您单独更改标签:
setTitle(_:forSegmentAtIndex:)
。所以你只需像这样在你的分段控件上使用它:
self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)
由于您将变量声明为 "weak",它会在您分配后立即被释放。但是无论如何你都不应该这样做,因为它是@IBOutlet -> 你应该通过接口构建器连接它。
至于更改标题,而不是仅仅创建新的 SC,使用
self.viewPicker.setTitle("", forSegmentAtIndex: index)
并隐藏/显示分段控件,
self.viewPicker.hidden = true / false
希望对您有所帮助!
对于 Swift 3.0 使用:
self.viewPicker.setTitle("Description", forSegmentAt: 0)
self.viewPicker.setTitle("Location", forSegmentAt: 1)