How to programmatically add a UISegmentedControl to a container view

后端 未结 7 951
情话喂你
情话喂你 2020-12-12 17:54

How would I define the frame for a UISegmentedControl? I would like the segmented control to appear at the bottom of a container view i.e UI

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 18:32

    Swift:

    let items = ["All Fruits", "Orange", "Grapes", "Banana"]
    let filtersSegment = UISegmentedControl(items: items)
    filtersSegment.frame = CGRect.init(x: 0, y: 0, width: 300, height: 50)
    filtersSegment.selectedSegmentIndex = 0
    filtersSegment.tintColor = UIColor.black
    filtersSegment.addTarget(self, action: #selector(self.filterApply), for: UIControlEvents.valueChanged)
    self.view.addSubview(filterSegment)
    
    @objc private func filterApply(segment: UISegmentedControl) -> Void {
        switch segment.selectedSegmentIndex {
        case 1:
            //Do something for Orange
        case 2:
            //Do something for Grapes
        case 3:
            //Do something for Banana
        default:
            //Do something for All Fruits
        }
    }
    

提交回复
热议问题