UISegmentedControl 代码方式创建

2017-10-16  本文已影响0人  iOSDeveloper

在ios11中,storyboard上面UINavigationBar中直接添加SegmentedControl后不能使用,所以可以通过代码形式创建。

override func viewDidLoad() {

super.viewDidLoad()

//分段选项显示

let items = ["精选","频道"]

//初始化对象

let segmentedControl = UISegmentedControl(items:items)

//设置位置

segmentedControl.frame = CGRect(x: (self.navigationController?.view.frame.width)!/2-60, y: (self.navigationController?.navigationBar.frame.height)!/2 - 12.5, width: 120, height: 25)

segmentedControl.tintColor = UIColor(red: 75/255, green: 191/255, blue: 240/255, alpha: 1)

//当前选中下标

segmentedControl.selectedSegmentIndex = 0

//添加事件

segmentedControl.addTarget(self, action: #selector(segmentedControlChanged), for: UIControlEvents.valueChanged)

//添加

self.navigationController?.navigationBar.addSubview(segmentedControl)

// Do any additional setup after loading the view.

}

//选择点击后的事件

@objc func segmentedControlChanged(sender:UISegmentedControl) {

print(sender.selectedSegmentIndex)

}

上一篇下一篇

猜你喜欢

热点阅读