2017-03-23 103 views
-2

您好,我在設計UISegmentControl的時候在swift 3.0中通過添加目標來編程,但請幫助我。如何以編程方式在swift 3.0中添加UISegmentedControl?

+0

確定。如果您現在無法啓動您的應用或崩潰,請提供一些代碼。沒有人知道你的問題與UISegmentControl。 –

+0

其實我試過這個客觀的c代碼,並將其轉換爲swift3.0但不工作 segmentedControl = UISegmentedControl(items:[「First」,「Second」,「Third」]) segmentedControl.frame = CGRectMake(60, 250,200,30) segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(個體經營,行動: 「segmentedControlAction:」 forControlEvents:.ValueChanged) self.view.addSubview(segmentedControl) – Shital

回答

7

嘗試此鏈接:

ADDING A SEGMENTED CONTROL PROGRAMMATICALLY

更新時間:

import UIKit 

class ViewController: UIViewController { 

    /** 
    Loads the view and in our case we override default loadView to provide 
    custom SegmentedControl. 
    */ 
    override func loadView() { 
     super.loadView() 
     self.view.backgroundColor = UIColor.purpleColor() 

     println("Main view's loadView() called.") 

     // Initialize 
     let items = ["Purple", "Green", "Blue"] 
     let customSC = UISegmentedControl(items: items) 
     customSC.selectedSegmentIndex = 0 

     // Set up Frame and SegmentedControl 
     let frame = UIScreen.mainScreen().bounds 
     customSC.frame = CGRectMake(frame.minX + 10, frame.minY + 50, 
            frame.width - 20, frame.height*0.1) 

     // Style the Segmented Control 
     customSC.layer.cornerRadius = 5.0 // Don't let background bleed 
     customSC.backgroundColor = UIColor.blackColor() 
     customSC.tintColor = UIColor.whiteColor() 

     // Add target action method 
     customSC.addTarget(self, action: "changeColor:", forControlEvents: .ValueChanged) 

     // Add this custom Segmented Control to our view 
     self.view.addSubview(customSC) 
    } 

    /** 
    Handler for when custom Segmented Control changes and will change the 
    background color of the view depending on the selection. 
    */ 
    func changeColor(sender: UISegmentedControl) { 
     println("Change color handler is called.") 
     print("Changing Color to ") 
     switch sender.selectedSegmentIndex { 
     case 1: 
      self.view.backgroundColor = UIColor.greenColor() 
      println("Green") 
     case 2: 
      self.view.backgroundColor = UIColor.blueColor() 
      println("Blue") 
     default: 
      self.view.backgroundColor = UIColor.purpleColor() 
      println("Purple") 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

來源:http://www.richardhsu.me/

+0

謝謝ANKIT但我不能打開上面的鏈接,請建議任何其他。 – Shital

+0

現在已更新。請檢查 –

+0

它的工作。抱歉回覆晚了。 – Shital

相關問題