swift 学习之UISegmentedControl

时间:2022-06-11 13:38:15
//创建分段控件的标题
        let titileArray:[String] = ["点评", "哪里逃"]
        let segment = UISegmentedControl(items: titileArray)
        //默认选中下标
        segment.selectedSegmentIndex = 0
        segment.addTarget(self, action: "click:", forControlEvents: UIControlEvents.ValueChanged)
        self.navigationItem.titleView = segment
        //在坐标为2的位置插入一个分段图片
         segment.insertSegmentWithImage(UIImage(named: "car")!, atIndex: 2, animated: true)
        //在坐标为1 的位置插入一个分段标题
        segment.insertSegmentWithTitle("插入新", atIndex: 1, animated: true)
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: (Tools().SCREEN_WIDTH - 30) / 3, height: (Tools().SCREEN_WIDTH - 30) / 3)
        //清除segment的背景色
        segment.tintColor = UIColor.clearColor()
       
        //设置segment字体选中和非选中时的状态
        let normalFont = UIFont(name: "Helvetica", size: 16.0)
        let normalTextAttributes: [NSObject : AnyObject] = [
            NSForegroundColorAttributeName: UIColor.blackColor(),
            NSFontAttributeName: normalFont!
        ]
        let selctedTextAttributes: [NSObject : AnyObject] = [
            NSForegroundColorAttributeName: UIColor.redColor(),
            NSFontAttributeName: normalFont!
        ]
        segment.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
        segment.setTitleTextAttributes(selctedTextAttributes, forState: .Selected)
        //获取某一个下标下的标题
        let titleT = segment.titleForSegmentAtIndex(0)
        print(titleT)
        //获取某一个下表下的图片
        let image = segment.imageForSegmentAtIndex(3)
        print(image)
        //设置下标为2的分段的宽度为80
        segment.setWidth(80, forSegmentAtIndex: 2)
        //获取某一个下标segment的宽度
        let width = segment.widthForSegmentAtIndex(2)
        print(width)
    func click(seg:UISegmentedControl){
       
        switch seg.selectedSegmentIndex {
        case 0:
            print("00000000000")
        case 1:
            print("1111111111")
        case 2:
            print("222222222222")
        case 3:
            print("33333333333")
        default:
            print("default")
        }
    }