-1

自定义按钮.swift

class CustomButton: UIButton {

    override func draw(_ rect: CGRect) {
        //drawing code
    }
}

ViewController.swift

let testCustom = CustomButton()
testCustom.draw(CGRect(x: 0, y: 0, width: 0, height: 0))
testCustom.isUserInteractionEnabled = true
testCustom.addTarget(self, action: #selector(Start(_:)), for: .touchUpInside)
self.view.addSubview(testCustom)

@objc func Start(_ sender: CustomButton) {
    print("pressed start")
}

按钮出现在屏幕上,但按下按钮时不会调用该功能。任何想法为什么?

我还尝试了 CustomButton.swift 中的函数和 addTarget 代码,但也无法触发。

谢谢你的帮助!

4

2 回答 2

0

@MuhammadWaqasBhati 很好地询问了框架。

我正在使用 addSublayer 将我创建的路径绘制到屏幕上。我的错误是我在 draw() 函数中设置值并使用 addSublayer 添加 CAShapeLayer,但是没有设置按钮的框架。

即使绘制的图层是按钮的子图层,它也会出现在为图层提供的坐标和尺寸上,与其“父”按钮的框架没有任何关系。

按钮的边框可以是 (0, 0, 0, 0) 或 (0, 0, 100, 100) 并且在 addSublayer 中绘制的图像仍然可以在 (250, 200, 75, 80) 以便可见图像将在屏幕的一个位置,但实际按钮位于与其子层中可见的内容无关的位置。

于 2019-04-10T02:27:15.433 回答
0

以下是如何UIButton在视图控制器 ( UIViewController) 中实例化子类的简单示例。它在 Swift 4.2 下进行了测试。

// Subclassing UIButton //
import UIKit

class MyButton: UIButton {
    var tintColor0: UIColor!
    var tintColor1: UIColor!
    var borderColor: UIColor!
    var backColor: UIColor!
    var cornerRadius: CGFloat!

    required init(frame: CGRect, tintColor0: UIColor, tintColor1: UIColor, borderColor: UIColor, backColor: UIColor, cornerRadius: CGFloat, titleString: String) {
        super.init(frame: frame)

        self.tintColor0 = tintColor0
        self.tintColor1 = tintColor1
        self.borderColor = borderColor
        self.backColor = backColor
        self.cornerRadius = cornerRadius
        self.setTitle(titleString, for: .normal)
    }

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

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        self.setTitleColor(tintColor0, for: .normal)
        self.setTitleColor(tintColor1, for: .highlighted)
        self.layer.borderColor = borderColor.cgColor
        self.layer.cornerRadius = cornerRadius
        self.layer.borderWidth = 1.0
        self.layer.backgroundColor = backColor.cgColor
    }
}

// View controller //
import UIKit

class ViewController: UIViewController {
    // MARK: - Variables

    // MARK: - IBOutlet

    // MARK: - IBAction

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        let buttonRect = CGRect(x: 20.0, y: 160.0, width: 100.0, height: 32.0)
        let myButton = MyButton(frame: buttonRect, tintColor0: UIColor.black, tintColor1: UIColor.gray, borderColor: UIColor.orange, backColor: UIColor.white, cornerRadius: 8.0, titleString: "Hello")
        myButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        view.addSubview(myButton)
    }

    @objc func buttonTapped(_ sender: UIButton) {
        print("Hello!?")
    }
}
于 2019-03-28T10:17:55.507 回答