Почему этот метод не может быть вызван?

#ios #swift

#iOS #swift

Вопрос:

Я только что клонировал проект из GitHub и добавил соответствующую папку в свой проект. Когда я запускаю свой проект, эффект анимации может отображаться нормально, но изображения в анимации не могут отображаться. Я попытался повторно клонировать полный код, но он по-прежнему делает то же самое. Я уверен, что все коды и изображения полностью клонированы.

Я добавил точку останова, понимая, что функция circleMenu никогда не вызывается. Может кто-нибудь, пожалуйста, объяснить это или, по крайней мере, сказать мне, что мне нужно написать, чтобы все было правильно?

Вот мой код:

 import UIKit

import CircleMenu

extension UIColor {
    static func color(_ red: Int, green: Int, blue: Int, alpha: Float) -> UIColor {
        return UIColor(
            red: 1.0 / 255.0 * CGFloat(red),
            green: 1.0 / 255.0 * CGFloat(green),
            blue: 1.0 / 255.0 * CGFloat(blue),
            alpha: CGFloat(alpha))
    }
}

class FirstViewController: UIViewController, CircleMenuDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    @IBAction func to2(_ sender: UIButton) {
        let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
        let view2 = sb.instantiateViewController(withIdentifier: "view2")
        layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
        self.present(view2,animated: true,completion: nil)
    }
    //    let secondView = ViewController()
    @IBAction func toView2(_ sender: UIButton) {
        let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
        let secondViewController = sb.instantiateViewController(withIdentifier: "SecondViewController")
        layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
        self.present(secondViewController,animated: true,completion: nil)
    }
    var imagePickerController:UIImagePickerController!

    enum TransitionAnimType : Int {
        case fade = 0,              
        push,                       
        reveal,                     
        moveIn,                     
        cube,                       
        suckEffect,                 
        oglFlip,                    
        rippleEffect,               
        pageCurl,                   
        pageUnCurl,                 
        cameraIrisHollowOpen,       
        cameraIrisHollowClose,      
        curlDown,                   
        curlUp,                     
        flipFromLeft,               
        flipFromRight,              
        ramdom                      
    }
    enum TransitionSubType : Int {
        case top = 0,               
        left,                       
        bottom,                     
        right,                      
        ramdom                      
    }

    enum TransitionCurve : Int {
        case Default = 0,           
        EaseIn,                     
        EaseOut,                    
        EaseInEaseOut,              
        Linear,                     
        Ramdom                      
    }
    private func animationType(animType: TransitionAnimType) -> String {
        let animTypeArray = ["fade", "push", "reveal", "moveIn", "cube",  "suckEffect", "oglFlip", "rippleEffect", "pageCurl", "pageUnCurl", "cameraIrisHollowOpen", "cameraIrisHollowClose", "curlDown", "curlUp", "flipFromLeft", "flipFromRight", "ramdom"]
        return objectFromDataSource(array: animTypeArray, index: animType.rawValue, isRamdom: (TransitionAnimType.ramdom == animType)) as! String
    }

    private func animationSubType(subType: TransitionSubType) -> String {
        let animSubTypeArray = [CATransitionSubtype.fromTop, CATransitionSubtype.fromLeft, CATransitionSubtype.fromBottom, CATransitionSubtype.fromRight]
        return objectFromDataSource(array: animSubTypeArray, index: subType.rawValue, isRamdom: (TransitionSubType.ramdom == subType)) as! String
    }

    private func animationCurve(curve: TransitionCurve) -> String {
        let animCurveArray = [CAMediaTimingFunctionName.default, CAMediaTimingFunctionName.easeIn, CAMediaTimingFunctionName.easeOut, CAMediaTimingFunctionName.easeInEaseOut, CAMediaTimingFunctionName.linear]
        return objectFromDataSource(array: animCurveArray, index: curve.rawValue, isRamdom: (TransitionCurve.Ramdom == curve)) as! String
    }

    private func objectFromDataSource(array: Array<Any>, index: Int, isRamdom: Bool) -> AnyObject {
        let count = array.count
        let i = isRamdom ? Int(arc4random_uniform(UInt32(count))) : index

        return array[i] as AnyObject
    }
    func layerTransition(animTye: TransitionAnimType, subType: TransitionSubType, curve: TransitionCurve, duration: CGFloat, layer: CALayer) {
        let key = "transition"
        if layer.animation(forKey: key) != nil {
            layer.removeAnimation(forKey: key)
        }
        let transition = CATransition()


        transition.duration = CFTimeInterval(duration)


        transition.type = CATransitionType(rawValue: animationType(animType: animTye))


        transition.subtype = CATransitionSubtype(rawValue: animationSubType(subType: subType))


        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName(rawValue: animationCurve(curve: curve)))


        transition.isRemovedOnCompletion = true

        layer.add(transition, forKey: key)

    }


    //    let colors = [UIColor.redColor(), UIColor.grayColor(), UIColor.greenColor(), UIColor.purpleColor()]
    let items: [(icon: String, color: UIColor)] = [
        ("icon_home", UIColor(red: 0.19, green: 0.57, blue: 1, alpha: 1)),
        ("icon_search", UIColor(red: 0.22, green: 0.74, blue: 0, alpha: 1)),
        ("notifications-btn", UIColor(red: 0.96, green: 0.23, blue: 0.21, alpha: 1)),
        ("settings-btn", UIColor(red: 0.51, green: 0.15, blue: 1, alpha: 1)),
        ("nearby-btn", UIColor(red: 1, green: 0.39, blue: 0, alpha: 1))
    ]
//    @IBInspectable var buttonsCount: Int = 3
//    @IBInspectable var duration: Double = 2 // circle animation duration
//    @IBInspectable var distance: Float = 100 // distance between center button and buttons
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {

    }
    // MARK: <CircleMenuDelegate>

    func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
        button.backgroundColor = items[atIndex].color

        button.setImage(UIImage(named: items[atIndex].icon), for: .normal)
        let image = UIImage(named:items[atIndex].icon)

        // set highlited image
        let highlightedImage = UIImage(named: items[atIndex].icon)?.withRenderingMode(.alwaysTemplate)
        button.setImage(highlightedImage, for: .highlighted)
        button.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
    }

    func circleMenu(_: CircleMenu, buttonWillSelected _: UIButton, atIndex: Int) {
        print("button will selected: (atIndex)")
    }

    func circleMenu(_: CircleMenu, buttonDidSelected _: UIButton, atIndex: Int) {
//        let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
//        let secondView = sb.instantiateViewController(withIdentifier: "secondView")
        print("button did selected: (atIndex)")
        if(atIndex == 0)
        {
            if(UIImagePickerController.isSourceTypeAvailable(.camera))
            {
                self.imagePickerController = UIImagePickerController()
                self.imagePickerController.delegate = self
                self.imagePickerController.allowsEditing = true
                self.imagePickerController.sourceType = UIImagePickerController.SourceType.camera
                layerTransition(animTye: .cameraIrisHollowOpen, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
                self.present(self.imagePickerController,animated: true,completion: nil)
            }
        }
    }
}

  

Комментарии:

1. пожалуйста, поделитесь с нами примером кода!

2. let image = UIImage(named:items[atIndex].icon) у вас есть ресурсы в проекте? ` UIImage(с именем:items[atIndex].icon` возвращает ноль?

3. Я следую вашему шагу. Он работает нормально. Пожалуйста, обратитесь к этому образцу исходного кода drive.google.com/file/d/1LkxD_CoCJtV556hzXvN6p9ncZu5twZGu /…

4. Где и как вы используете CircleMenu? Вы импортируете фреймворк CircleMenu и добавили методы делегирования, но где вы устанавливаете делегат?

5. я считаю, что circleMenu — это методы делегирования, и они никогда не будут вызваны, пока не будут запущены некоторые делегаты.

Ответ №1:

На данный момент вы только объявляете свой делегат. Убедитесь, что вы также установили делегат, иначе ваши методы делегирования не были бы вызваны.