Swift:以编程方式更改我的UISegmentedControl的项目

时间:2023-01-16 16:24:32

I want to change the items in my UISegmentedControl based off of another selection. I do not want to change the number of items, but simply the item labels, as well as the 'hidden' variable of the UISegmentedControl.

我想根据其他选择更改我的UISegmentedControl中的项目。我不想更改项目数,只需更改项目标签,以及UISegmentedControl的“隐藏”变量。

Here is my code to get the UISegmentedControl:

这是获取UISegmentedControl的代码:

@IBOutlet weak var viewPicker: UISegmentedControl!

and here is the code to change it:

这是改变它的代码:

viewPicker = UISegmentedControl(items: ["Description", "Location"])

However, this doesn't work and sometimes sets viewPicker to nil, giving an error. What is the best way to do this?

但是,这不起作用,有时会将viewPicker设置为nil,从而产生错误。做这个的最好方式是什么?

3 个解决方案

#1


4  

Since you are declaring your variable as "weak", it will get deallocated as soon as you assign it. But you should not do it anyway, because it is @IBOutlet -> you should connect it through interface builder.

由于您将变量声明为“弱”,因此一旦分配它就会被释放。但是你不应该这样做,因为它是@IBOutlet - >你应该通过界面构建​​器连接它。

As for changing the title, instead of just creating new SC, use

至于更改标题,而不是仅创建新的SC,请使用

self.viewPicker.setTitle("", forSegmentAtIndex: index)

And to hide / show segmented control,

并隐藏/显示分段控制,

self.viewPicker.hidden = true / false

Hope it helps!

希望能帮助到你!

#2


3  

The UISegmentControl has a method that lets you change the labels individually called: setTitle(_:forSegmentAtIndex:). So you just use it on your segmented control like so:

UISegmentControl有一个方法,允许您单独更改名称:setTitle(_:forSegmentAtIndex :)。所以你只需在你的分段控件上使用它,如下所示:

self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)

#3


0  

For Swift 3.0 use:

对于Swift 3.0使用:

 self.viewPicker.setTitle("Description", forSegmentAt: 0)
 self.viewPicker.setTitle("Location", forSegmentAt: 1)

#1


4  

Since you are declaring your variable as "weak", it will get deallocated as soon as you assign it. But you should not do it anyway, because it is @IBOutlet -> you should connect it through interface builder.

由于您将变量声明为“弱”,因此一旦分配它就会被释放。但是你不应该这样做,因为它是@IBOutlet - >你应该通过界面构建​​器连接它。

As for changing the title, instead of just creating new SC, use

至于更改标题,而不是仅创建新的SC,请使用

self.viewPicker.setTitle("", forSegmentAtIndex: index)

And to hide / show segmented control,

并隐藏/显示分段控制,

self.viewPicker.hidden = true / false

Hope it helps!

希望能帮助到你!

#2


3  

The UISegmentControl has a method that lets you change the labels individually called: setTitle(_:forSegmentAtIndex:). So you just use it on your segmented control like so:

UISegmentControl有一个方法,允许您单独更改名称:setTitle(_:forSegmentAtIndex :)。所以你只需在你的分段控件上使用它,如下所示:

self.viewPicker.setTitle("Description", forSegmentAtIndex:0)
self.viewPicker.setTitle("Location", forSegmentAtIndex:1)

#3


0  

For Swift 3.0 use:

对于Swift 3.0使用:

 self.viewPicker.setTitle("Description", forSegmentAt: 0)
 self.viewPicker.setTitle("Location", forSegmentAt: 1)