码迷,mamicode.com
首页 > 编程语言 > 详细

Swift - UISegmentedControl

时间:2019-01-06 11:56:18      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:control   string   add   图片   objc   class   self   enter   系统默认   

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let items = ["optionA","optionB","optionC"]
        let segmented = UISegmentedControl(items: items)
        //设置中心位置
        segmented.center = self.view.center
        //设置默认选中的索引,索引从0开始
        segmented.selectedSegmentIndex = 1
        //添加监听事件
        segmented.addTarget(self, action: #selector(ViewController.SegmentedChanged(_:)), for: .valueChanged)
        //添加文字选项
        segmented.insertSegment(withTitle: "option D", at: 4, animated: true)
        //添加图片选项(withRenderingMode(.alwaysOriginal)设置图片颜色为原颜色,而不是系统默认的蓝色)
        segmented.insertSegment(with: UIImage(named:"Icon")?.withRenderingMode(.alwaysOriginal), at: 1, animated: true)
        //移除指定选项
        segmented.removeSegment(at: 1, animated: true)
        //移除全部选项
//        segmented.removeAllSegments()
        //修改选项颜色
        segmented.tintColor = UIColor.blue
        //修改选项文字
        segmented.setTitle("newName", forSegmentAt: 3)
        //修改选项图片
        segmented.setImage(UIImage(named: "newIcon"), forSegmentAt: 1)
        //修改选项内容偏移位置
        segmented.setContentOffset(CGSize(width: 5, height: 5), forSegmentAt: 1)
        //添加到视图中
        self.view.addSubview(segmented)
    }
    @objc func SegmentedChanged(_ segmented:UISegmentedControl)
    {
        //打印选项的索引
       print("index is \(segmented.selectedSegmentIndex)")
        //打印选择的文字
        print("option is \(String(describing: segmented.titleForSegment(at: segmented.selectedSegmentIndex)))")//将获得值转为String类型
    }

}

Swift - UISegmentedControl

标签:control   string   add   图片   objc   class   self   enter   系统默认   

原文地址:https://www.cnblogs.com/iOS-Development/p/10227411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!