分段选择控件(UISegmentedControl)

//选项除了文字还可以是图片
        let arr = ["第一类","第二类",UIImage(named:"93-dot-red")!] as [Any]
        
        let seg = UISegmentedControl(items: arr)
        seg.frame = CGRect(x: 50, y: 200, width: 200, height: 30)
        //默认选择第几项
        seg.selectedSegmentIndex = 1//0,1,2
        
        seg.addTarget(self, action: #selector(segClick(_:)), for: .valueChanged)
        
        //
        seg.insertSegment(withTitle: "第四类", at: 3, animated: true)
        seg.insertSegment(with: UIImage(named:"93-dot-red"), at: 4, animated: true)
        
        self.view.addSubview(seg)
        

    //_ seg中间有空格
    func segClick(_ seg:UISegmentedControl)
    {
        //获得选项的索引
        print("\(seg.selectedSegmentIndex)")
        //获得选择的文字
        print("\(seg.titleForSegment(at: seg.selectedSegmentIndex))")
    }

你可能感兴趣的:(分段选择控件(UISegmentedControl))