在 Swift 中对作为 UIView 扩展的 class 进行动画处理

Animating a class that is an extension of UIView in Swift

我正在尝试使用 appear() 函数让我的选项 class 的实例在屏幕上显示动画,按下 SearchResult [=25] 中的按钮时激活=] 但我遇到了麻烦,该实例已作为子视图添加到 ViewController Class.

中的视图

我已经能够在 ViewController 中使用函数 optionMenu.appear() 并且它可以正常工作,但是当通过单击 SearchResult 中的按钮调用它时,它似乎执行除动画之外的所有操作,正如我在 optionMenu.appear() 中测试过的打印并成功打印一样。

import Foundation
import UIKit

class SearchResult {

    private let link: String

    var body = UIView()

    init(_ link: String){

        self.link = link

        let options = UIButton(x: Int(body.bounds.width-60), y: 10, size: 50.0)
        options.addTarget(self, action: #selector(optionsClicked), for: .touchUpInside)
        body.addSubview(options)

    }

    @objc func optionsClicked(){
        ViewController().optionMenu.appear()
    }
}
import Foundation
import UIKit

class Options: UIView{

    var buttons = [UIButton]()
    private var link = String()

    init(_ titles: [String]){
        let height = ((titles.count+1)*65)+5
        super.init(frame: CGRect(x: 0, y: Int(UIScreen.main.bounds.height)-height, width: Int(UIScreen.main.bounds.width), height: height))
        var i = 0
        for title in titles{
            let button = UIButton(frame: CGRect(x: 5, y: 5+(i*65), width: Int(UIScreen.main.bounds.width)-10, height: 60))
            button.setTitle(title, for: .normal)
            buttons.append(button)
            self.addSubview(button)
            i += 1
        }
        let cancel = UIButton(frame: CGRect(x: 5, y: 5+(i*65), width: Int(UIScreen.main.bounds.width)-10, height: 60))
        cancel.setTitle("cancel", for: .normal)
        self.addSubview(cancel)        
    }

    func appear(){
        UIView.animate(withDuration: 0.2, animations: {
            self.transform = CGAffineTransform(translationX: 0, y: -self.bounds.height)
        })
    }

    @objc func disappear(){
        UIView.animate(withDuration: 0.2, animations: {
            self.transform = CGAffineTransform.identity
        })
    }

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

因为你正在构建一个新的Viewcontroller,每次调用optionsClicked()时,调用都会出现在那个Viewcontroller的选项菜单中。您需要参考具有选项菜单的 viewController 并执行 myViewController.optionMenu.appear()