错误:点击UISegmentedControl时无法识别的选择器发送到实例

问题描述 投票:0回答:1

当点击这些片段之一以触发操作时出现错误。

知道我在做什么错吗?

错误:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[TestingSubclassing.MySegmentControl segmentActionWithSender:]:无法识别的选择器已发送到实例0x7f9217907750'

import UIKit

class MySegmentControl: UISegmentedControl {

    var actionName:Selector
    init(actionName: Selector) {
        self.actionName = actionName

        super.init(frame: .zero)

        insertSegment(withTitle: "Two", at: 0, animated: false)
        insertSegment(withTitle: "One", at: 1, animated: false)

        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: self.actionName, for: .valueChanged)

        self.translatesAutoresizingMaskIntoConstraints = false
    }

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

在ViewController中的用法

import UIKit

class ViewController: UIViewController {

    let segmentOne: MySegmentControl = {
        let segment1 = MySegmentControl(actionName:  #selector(segmentAction))
        return segment1
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(segmentOne)
    }

    @objc func segmentAction(sender: UISegmentedControl) {
        print("segmentAction")
    }
}

我也尝试过如下更改选择器。

let segment1 = MySegmentControl(actionName: #selector(segmentAction(sender:)))let segment1 = MySegmentControl(actionName: "segmentAction")

ios swift uisegmentedcontrol
1个回答
0
投票

您必须是新手!您应该删除self.addTarget(self, action: self.actionName, for: .valueChanged)中的class MySegmentControl,在功能viewDidLoad()下添加以下内容:

segmentOne.addTarget(self, action: #selector(segmentAction(sender:)), for: .valueChanged)
© www.soinside.com 2019 - 2024. All rights reserved.