子类化 UISegmentedControl 时设置“items”和目标操作时出错

Error setting `items` and target action when subclassing UISegmentControl

在下面的代码中,我有几个 UISegmentControl 是我以编程方式创建的,除了目标操作之外,所有段都是相同的。我想做的是将段控件的代码移到它自己的 class 但我 运行 遇到了几个问题。

如何设置 items 和子classing UISegmentControl 时的目标操作?

仅供参考 - 所有项目都相同。

这是我要移动到它自己的代码class。

let segmentOne: UISegmentedControl = {
    let items = ["One" , "Two"]
    let segment1 = UISegmentedControl(items: items)
    segment1.selectedSegmentIndex = 0

    segment1.layer.cornerRadius = 5.0
    segment1.backgroundColor = UIColor.red
    segment1.layer.borderWidth = 1
    segment1.layer.borderColor = UIColor.blue.cgColor

    segment1.addTarget(self, action: #selector(segmentDiscountTwoType), for: .valueChanged)
    return segment1
}()

这是我尝试过的方法,它给了我两个错误:

第一个错误:

'super.init' called multiple times in initializer

第二个错误:

Argument of '#selector' cannot refer to parameter 'actionName'

import UIKit

class MySegmentControl: UISegmentedControl{

    init(actionName: Selector){
        let discountItems = ["One" , "Two"]

        super.init(frame: .zero)
        super.init(items:discountItems)// first ERROR

        self.selectedSegmentIndex = 0

        self.layer.cornerRadius = 5.0
        self.backgroundColor = UIColor.red
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.blue.cgColor

       self.addTarget(self, action: #selector(actionName), for: .valueChanged) // second ERROR
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

第一个错误:

不要打电话给init(frame

第二个错误:

actionName 已经是 Selector

class MySegmentControl: UISegmentedControl {

    init(actionName: Selector) {
        let discountItems = ["One" , "Two"]
        super.init(items: discountItems)

        self.selectedSegmentIndex = 0

        self.layer.cornerRadius = 5.0
        self.backgroundColor = UIColor.red
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.blue.cgColor

        self.addTarget(self, action: actionName, for: .valueChanged)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}