18

The Segment name is Entrada. I am doing like this:

override func viewDidLoad() {
    super.viewDidLoad()

    Entrada(sender: UISegmentedControl) {
        setTitle("Action 1", forSegmentAtIndex: 0)
        setTitle("Action 2", forSegmentAtIndex: 1)
        setTitle("Action 3", forSegmentAtIndex: 2)
    }

I get errors... thow.

Cœur
  • 37,241
  • 25
  • 195
  • 267
fr0zt
  • 733
  • 4
  • 12
  • 30

3 Answers3

20

Swift 3.0 use:

 @IBOutlet weak var entrada : UISegmentedControl!

  override func viewDidLoad() {
  super.viewDidLoad()

  entrada.setTitle("Action 1", forSegmentAt: 0)
  entrada.setTitle("Action 2", forSegmentAt: 1)
  entrada.setTitle("Action 3", forSegmentAt: 2) 
 } 
Brian Bird
  • 1,176
  • 18
  • 21
8

You have to connect the segmented control to an IBOutlet in Interface Builder, then you can write

@IBOutlet var entrada : UISegmentedControl!

override func viewDidLoad() {
  super.viewDidLoad()

  entrada.setTitle("Action 1", forSegmentAtIndex: 0)
  entrada.setTitle("Action 2", forSegmentAtIndex: 1)
  entrada.setTitle("Action 3", forSegmentAtIndex: 2) 
} 

In Swift 3+ the syntax has been changed to

override func viewDidLoad() {
  super.viewDidLoad()

  entrada.setTitle("Action 1", forSegmentAt: 0)
  entrada.setTitle("Action 2", forSegmentAt: 1)
  entrada.setTitle("Action 3", forSegmentAt: 2) 
} 
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I hAVE done that below like this: @IBAction func Entrada(sender: UISegmentedControl) { code } But no success :( I get a messagem saying that Entrada has no setTitle member – fr0zt Dec 24 '15 at 15:16
  • This is an `IBAction` which is called when the segmented control is tapped, an `IBOutlet` is a reference to an UI element in interface Builder. Interpreting the title of your question you need `IBOutlet` – vadian Dec 24 '15 at 15:19
  • Done that but now it crashes... :( – fr0zt Dec 24 '15 at 15:34
  • Have you also connected the `IBOutlet` in Interface Builder by control-dragging to the class object (the little circle left from the declaration line must be dark)? – vadian Dec 24 '15 at 15:37
  • Can you please explain how to do that? I've been looking for it whithout success – fr0zt Dec 24 '15 at 16:21
  • The easiest way to create outlets is described in the documentation: https://developer.apple.com/library/ios/recipes/xcode_help-IB_connections/chapters/CreatingOutlet.html – vadian Dec 24 '15 at 16:27
1

You can use below code snippet to setup titles of your segment control. Just pass an array of string to set titles.

Swift 4+

func segmentWithTitles(titles : [String])  {
        self.friendsSegment.setTitle(titles[0], forSegmentAt: 0)
        self.friendsSegment.setTitle(titles[1], forSegmentAt: 1)
        self.friendsSegment.setTitle(titles[2], forSegmentAt: 2)
    }