实例化 UISegementedControl 的子类时,将未实现的初始化程序“init(frame:)"用于类 [英] Use of unimplemented initializer 'init(frame:)' for class when instantiating a subclass of UISegementedControl

查看:17
本文介绍了实例化 UISegementedControl 的子类时,将未实现的初始化程序“init(frame:)"用于类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在下面的代码中使用 MySegmentControl 的实例时,出现以下错误.该错误在应用启动后立即发生.

I'm getting the following error when I try to use an instance of MySegmentControl in the code below. The error occurs right after the app is being launched.

知道我错过了什么吗?

致命错误:对类TestingSubclassing.MySegmentControl"使用未实现的初始化程序init(frame:)"

Fatal error: Use of unimplemented initializer 'init(frame:)' for class 'TestingSubclassing.MySegmentControl'

UISegementedControl 的子类

导入 UIKit

Subclass of UISegementedControl

import UIKit

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")
    }
}

视图控制器

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")
    }
}

推荐答案

您可以调用 super.init(frame手动插入片段.

You could call super.init(frame and insert the segments manually.

并且您必须将 target 参数添加到自定义 init(actionName 方法.

And you have to add a target parameter to the custom init(actionName method.

class MySegmentControl: UISegmentedControl {

    init(actionName: Selector, target: Any?) {
        super.init(frame: .zero)

        insertSegment(withTitle: "Two", at: 0, animated: false)
        insertSegment(withTitle: "One", at: 0, 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(target, action: actionName, for: .valueChanged)
    }

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

这篇关于实例化 UISegementedControl 的子类时,将未实现的初始化程序“init(frame:)"用于类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆