import UIKit
class ViewController: UIViewController {
// @IBAction func Btndel(_ sender: Any) {
//}
var Str:String?
override func viewDidLoad() {
super.viewDidLoad()
let items = [Str]
let SegM = UISegmentedControl(items:items as Any as? [Any])
SegM.selectedSegmentIndex = 0
SegM.frame=CGRect(x: 70, y: 130, width: 100, height: 50)
SegM.layer.cornerRadius = 8.0
SegM.backgroundColor = .orange
SegM.tintColor = .white
self.view .addSubview(SegM)
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func Btnadd(_ sender: Any)
{
var Str = 0;Str += 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如何通过单击添加按钮和在同一视图控制器中创建的删除按钮来在视图控制器中添加和删除细分
答案 0 :(得分:0)
您可以通过UISegmentedControl的 insertSegment 方法插入细分,也可以通过 removeSegment 方法删除细分。让我举个例子。
我在情节提要中创建 segmentController 类及其UI。 以下是UI屏幕截图。在情节提要中,您可以看到两个按钮:插入(+)和删除(-)以及UISegmentedControl。 “插入”按钮将在特定位置插入线段,“移除”按钮将在特定位置删除线段。
下面是 segmentController 类的代码。
class segmentController: UIViewController {
@IBOutlet weak var segementControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func remove(_ sender: Any) {
segementControl.removeSegment(at: segementControl.numberOfSegments-1, animated: true)
}
@IBAction func insert(_ sender: Any) {
segementControl.insertSegment(withTitle: "\(segementControl.numberOfSegments+1)", at: segementControl.numberOfSegments, animated: true)
}
}
在上面的代码中,在插入按钮上单击新段,将在segementControl的最后添加。在删除按钮上,单击最后一个片段将从segmentControl中删除。
希望有帮助。
答案 1 :(得分:0)
如何在swift4中插入和删除(添加或删除)段
ViewController类:UIViewController {
@IBOutlet weak var segment1: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func insert(_ sender: Any) {
segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)
}
@IBAction func remove(_ sender: Any) {
segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
}
}