Swift 之UISegmentedControl

1、创建

 var items = ["选项一","选项二","选项三"]

  /************************************/

   另外一种是在选项中添加图片,不过图片要进行防渲染处理

    var  image = UIImage(named:"2")
    image = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
    let items = ["选项一","选项二", image as Any] as [Any]

   /************************************/

  let segmented = UISegmentedControl.init(items: items)

  //设置位置及大小 有下面的中心center,前边位置失效

  segmented.frame = CGRect.init(x: 0, y: 0, width: 240, height: 80)
  segmented.center = self.view.center

   // 默认选择第几个

  segmented.selectedSegmentIndex = 1

  //控件中所有颜色都统一换成这种颜色

   segmented.tintColor = UIColor.orange


  self.view.addSubview(segmented)

2、选择控件基本设置

      //修改某个索引选项的文字

      segmented.setTitle("swift", forSegmentAt: 1)

     //修改某个索引选项为图片(防图片渲染方法在上边)

     segmented.setImage(UIImage(named:"1"), forSegmentAt: 1)

     //选项内容的偏移距离

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

     //选项内容的插入和删除

      segmented.insertSegment(withTitle: "hha", at: 1, animated: true)

      segmented.insertSegment(with: UIImage(named:"1"), at: 1, animated: true)

      segmented.removeSegment(at: 1, animated: true)

      segmented.removeAllSegments()

3、选择控件获得选择的值

      segmented.addTarget(self, action: #selector(segmentChange(_:)), for: UIControlEvents.valueChanged)

      func segmentChange(_ segmented:UISegmentedControl) {
        print(segmented.selectedSegmentIndex)
      }

4、选择和未选择颜色

      segmented.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.red], for: UIControlState.normal)
        
      segmented.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for: UIControlState.selected)

5、可以设置边框和颜色

      segmented.layer.borderColor = UIColor.black.cgColor
        
      segmented.layer.borderWidth = 1

 

阅读更多
个人分类: swift
上一篇UISwitch
下一篇Swift 之 UIImageView
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭