ios - 将 subview 添加到自定义 UI 按钮类

标签 ios swift

目标:

When the user clicks the custom button, a blank UIView should appear covering the button.

我已经将我的代码添加到一个新的 Swift 项目中,如下所示

import UIKit

class DownloadUIButton: UIButton {
    var isDownloading: Bool? = false
    func addView() {
        let view = UIView(frame: self.frame)
        view.backgroundColor = UIColor.white
        self.addSubview(view)
    }
}

class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {

    fileprivate let tableView: UITableView = UITableView(frame: CGRect.init(x: 0, y: 0, width: 300, height: 300), style: UITableViewStyle.plain)

    override func viewDidLoad() {
        self.setupTableView()

    }

    fileprivate func setupTableView() {
        self.tableView.dataSource = self
        self.tableView.delegate = self
        tableView.backgroundColor = UIColor.white
        tableView.isOpaque = true
        view.addSubview(self.tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "CellIdentifier")

        let buttonSize = 30
        let btn = DownloadUIButton(frame: CGRect(x: 10, y: 10, width: buttonSize, height: buttonSize))
        btn.backgroundColor = UIColor.red
        btn.addTarget(self, action:#selector(handleDownload(_:)), for: .touchUpInside)
        cell.addSubview(btn)

        return cell
    }

    @objc func handleDownload(_ btn: DownloadUIButton) {
        btn.addView()
    }

}

但是,项目报错:

2017-10-28 12:55:41.558522+0100 TestProject[21392:1779236] *** 由于未捕获的异常“CALayerInvalid”而终止应用程序,原因:“图层是其图层树中循环的一部分”

最佳答案

为了让一个 View 出现在你的按钮前面,我只是让它们成为具有相同框架的兄弟 View 。在启动时将自定义 View 的 isHidden 设置为 true,并在单击按钮时将按钮的 isHidden 设置为 true 和自定义 View 的 isHiddenfalse。或者,如果您确实希望按钮在自定义 View 的透明部分后面可见,您可以使用 sendSubview(toBack:) 使按钮出现在自定义 View 的后面。

关于ios - 将 subview 添加到自定义 UI 按钮类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46989361/

相关文章:

iOS:当应用程序状态为 UIApplicationStateBackground 时,为什么 dispatch_async 不会运行到主线程?

swift - 锁定按钮直到第二天

ios - 给 UIBarButton 添加阴影

ios - 使用 UserDefaults 获取和设置不保存字符串

ios - 尝试从 UITableView 中删除行时断言失败错误

iphone - 为什么 Core Data 使用 Z 前缀命名它在 SQLite 中创建的表和属性?

iphone - _myObject 与 self.myObject

ios - 在iOS应用中共享文档

ios - 使用 Swift 从文本文件中删除单词

swift - 如何使用按钮更改 NSCollectionView 的数据