Swift-use of segmented selection controls (Uisegmentedcontrol)-Basic usage

Source: Internet
Author: User

1, select the control's creation and listen for the control selection value 


Import UIKit
 
Class ViewController: UIViewController {
     
     Override func viewDidLoad() {
         super.viewDidLoad()
         
         //Options can be pictures in addition to text
         Let items = ["option one", "option two", UIImage(named: "g1")!] as [Any]
         Let segmented = UISegmentedControl(items:items)
         Segmented.center = self.view.center
         segmented.selectedSegmentIndex = 1 //The second item is selected by default
         segmented.addTarget(self, action: #selector(ViewController.segmentDidchange(_:)),
                             For: .valueChanged) //Add value change listener
         self.view.addSubview(segmented)
     }
     
     Func segmentDidchange(_ segmented:UISegmentedControl){
         / / Get the index of the option
         Print(segmented.selectedSegmentIndex)
         / / Get the selected text
         Print(segmented.titleForSegment(at: segmented.selectedSegmentIndex))
     }
}


2, select the selection of the control add and remove 


/ / Add text options
segmented.insertSegment(withTitle: "new option", at:1, animated:true);
/ / Add image options
segmented.insertSegment(with: UIImage(named:"icon")!, at:1, animated: true)
// remove option
segmented.removeSegment(at: 1, animated:true)


3, modify the option color (including picture options) 


 segmented.tintcolor= uicolor. Redcolor () 


4, modify option Text 


segmented.settitle ("Swfit", forsegmentatindex:1)


5, modify the option picture 

(1) The following code image will automatically turn blue


segmented.setImage(UIImage(named:"icon"), forSegmentAt:2)


(2) Use the code below to keep the original color


segmented.setImage(UIImage(named:"icon")?.withRenderingMode(.alwaysOriginal), forSegmentAt:2)


6, modify the option content offset location 


segmented.setContentOffset(CGSize(width:10, height:7), forSegmentAt:1)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.