ObjectAtIndex 索引 0 超出分段控件中空数组的范围

ObjectAtIndex index 0 beyond bounds for empty array in segmented Control

嗨,我想以编程方式进行分段控制,但在 运行 模拟器 "ObjectAtIndex index 0 beyond bounds for empty array" 时出错。我试图找到问题,但找不到。这是我的代码

    let segmentedControl    = GSegmentedControl(frame: .zero)
    let segmentedIndicator  = UIView()

    segmentedControl.setTitle("Daily", forSegmentAt: 0)
    segmentedControl.setTitle("Subject", forSegmentAt: 1)
    view.addSubview(segmentedControl)
    segmentedControl.addTarget(self, action: #selector(ViewController.indexChange(in:)), for: .valueChanged)

    @objc func indexChange(in segmented: UISegmentedControl) {
        let numberOfSegmented   = CGFloat(segmentedControl.numberOfSegments)
        let selectIndex         = CGFloat(segmented.selectedSegmentIndex)
        let titleCount          = CGFloat(segmentedControl.titleForSegment(at: segmented.selectedSegmentIndex)!.count)

        view.addSubview(segmentedIndicator)
        segmentedIndicator.backgroundColor = .systemPink
        segmentedIndicator.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            segmentedIndicator.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor, constant: 3),
            segmentedIndicator.heightAnchor.constraint(equalToConstant: 2),
            segmentedIndicator.widthAnchor.constraint(equalToConstant: CGFloat(15 + titleCount * 8)),
            segmentedIndicator.centerXAnchor.constraint(equalToSystemSpacingAfter: segmentedControl.centerXAnchor, multiplier: CGFloat(numberOfSegmented / CGFloat(3) + CGFloat(selectIndex-1.0) * 2.0))

        ])

        UIView.animate(withDuration: 0.5, animations: {
            self.view.layoutIfNeeded()
            self.segmentedIndicator.transform = CGAffineTransform(scaleX: 1.4, y: 1)
        }) { finish in
            UIView.animate(withDuration: 0.4) {
                self.segmentedIndicator.transform = .identity
            }
        }
    }

之间
let segmentedControl = GSegmentedControl(frame: .zero)

segmentedControl.setTitle("Daily", forSegmentAt: 0)
segmentedControl.setTitle("Subject", forSegmentAt: 1)

您没有设置 numberOfItems,因此您的计数为 0,但请尝试访问第一个(和第二个)索引。

要解决此问题,请更改初始化:

let segmentedControl = GSegmentedControl(items: ["Daily", "Subject"])

并删除 setTitle.. 行
或将 setTitle 行更改为

segmentedControl.insertSegment(withTitle: "Daily", at: 0, animated: false)
segmentedControl.insertSegment(withTitle: "Subject", at: 1, animated: false)