我如何使用UIView,UIButton子类呈现视图控制器?

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

所以我创建了这个UIButton子类。这是一个可重用的组件,可以添加到任何视图控制器中。我需要在按钮中点按来显示一个警报视图控制器。因此,基本上我需要找出按钮位于哪个视图控制器中,以便可以将视图控制器作为参数传递。

final class ProfileButton: UIButton {

let picker = UIImagePickerController()

lazy var shadowImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFill
    imageView.image = UIImage(named: "download")
    return imageView
}()

override public init(frame: CGRect) {
    super.init(frame: frame)
    setupSelf()
    self.addTarget(self, action: #selector(profileButtonTapped), for: .touchUpInside)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
}
override public func layoutSubviews() {
    super.layoutSubviews()
    shadowImageView.layer.cornerRadius = self.frame.width/2.70
    shadowImageView.layer.masksToBounds = true
}

@objc func profileButtonTapped(){
    imageHandler(presenter: )
}

@objc func imageHandler(presenter: UIViewController!){
    let alertController = UIAlertController(title: "Profile Picture", message: "Please select your profile picture", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction!) in
        print("I am working")
    })
    let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction!) in
        print("I am working")
    })

    alertController.addAction(okAction)
    alertController.addAction(cameraAction)
    presenter.present(alertController, animated: true, completion: nil)
}

我实际上需要找出视图控制器,以便可以在imageHandler(presenter:UIViewController)函数中传递它。

ios swift uiview uiviewcontroller uibutton
2个回答
0
投票

您可以在weak var中向控制器添加UIButton引用,如下所示:

final class ProfileButton: UIButton {
    weak var presenter: UIViewController?
    //...
    override public init(frame: CGRect) {
        super.init(frame: frame)
        setupSelf()
        addTarget(self, action: #selector(imageHandler), for: .touchUpInside)
    }
    //...
    @objc func imageHandler() {
        //...
        presenter?.present(alertController, animated: true, completion: nil)
    }
}

0
投票

在这种情况下,您可以使用此扩展名来获得顶级控制器

extension UIApplication {

    class func getTopMostViewController() -> UIViewController? {
        let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        if var topController = keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            return topController
        } else {
            return nil
        }
    }
}


@objc func imageHandler() {
        //...
        UIApplication.getTopMostViewController()?.present(alertController, animated: true, completion: nil)

    }
© www.soinside.com 2019 - 2024. All rights reserved.