SWreveal View Controller和Subview

时间:2015-08-24 14:04:00

标签: ios swift addsubview swrevealviewcontroller tinder

我正在开发一个应用程序,它允许用户使用swype手势(如果你喜欢或向右滑动,如果没有),要做到这一点,我正在使用一个库(使用addSubview),但是,我也使用SWRevealViewController来制作我的侧边菜单。

主要问题是,我不知道如何以编程方式在我的“addSubview”视图上实现手势。

当然我已经使用了:

self.view.addGestureRecognizer(self.revealViewController()。panGestureRecognizer())

但它不起作用。

谢谢!

这是我的两个主要控制器:

图书馆:

import UIKit

class KinderCardView: UIView {

private var isFliped: Bool = false
private var isAnimated: Bool = false

private var imageViewContent: UIImageView = {
    let imageView = UIImageView()
    imageView.layer.masksToBounds = true
    imageView.contentMode = UIViewContentMode.ScaleAspectFill
    return imageView
}()

private lazy var titleLabelContent: UILabel = {
    let label = UILabel()
    label.textAlignment = NSTextAlignment.Center
    label.textColor = UIColor.blackColor()
    label.font = UIFont.boldSystemFontOfSize(17)
    return label
}()

private lazy var descLabelContent: UITextView = {
    let desc = UITextView()
    desc.editable = false
    desc.font = UIFont.systemFontOfSize(17)
    desc.transform = CGAffineTransformMakeScale(-1, 1)
    desc.backgroundColor = UIColor.clearColor()
    desc.textColor = UIColor.grayColor()
    desc.selectable = false
    return desc
}()

var imageContent: UIImage! {
    get {
        return self.imageViewContent.image
    }
    set {
        self.imageViewContent.image = newValue
    }
}

var titleContent: String! {
    get {
        return self.titleLabelContent.text
    }
    set {
        self.titleLabelContent.text = newValue
        self.titleLabelContent.frame.origin = CGPointMake(10, ((self.frame.size.height - self.frame.size.width) / 2 -
            self.titleLabelContent.frame.size.height / 2) + self.frame.size.width)
    }
}

var descContent: String! {
    get {
        return descLabelContent.text
    }
    set {
        descLabelContent.text = newValue
    }
}

var size: CGSize! {
    get {
        return self.frame.size
    }
    set {
        self.frame.size = newValue
        self.imageViewContent.frame.size = CGSizeMake(self.frame.width, self.frame.width)
        self.titleLabelContent.frame.size = CGSizeMake(self.frame.size.width - 20, 30)
        self.titleLabelContent.frame.origin = CGPointMake(10, self.frame.size.width + 10)
    }
}

func flipCard() {
    if isAnimated {
        return
    }
    if isFliped == false {
        descLabelContent.frame.size = CGSizeMake(size.width - 20, size.height - 20)
        UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1,
            options: UIViewAnimationOptions.allZeros, animations: { () -> Void in
                self.transform = CGAffineTransformMakeScale(-1, 1)
                self.imageViewContent.alpha = 0
                self.titleLabelContent.alpha = 0
                self.descLabelContent.alpha = 1
                self.isAnimated = true
            }, completion: { (anim:Bool) -> Void in
                self.isAnimated = false
        })
        isFliped = true
    }
    else {
        UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.1,
            options: UIViewAnimationOptions.allZeros, animations: { () -> Void in
                self.transform = CGAffineTransformMakeScale(1, 1)
                self.imageViewContent.alpha = 1
                self.titleLabelContent.alpha = 1
                self.descLabelContent.alpha = 0
                self.isAnimated = true
            }, completion: { (anim:Bool) -> Void in
                self.isAnimated = false
        })
        isFliped = false
    }

}

override init(frame: CGRect) {
    super.init(frame: frame)
}

init(size: CGSize) {
    super.init(frame: CGRectMake(0, 0, size.width, size.height))
    self.backgroundColor = UIColor.whiteColor()

    self.layer.borderWidth = 5
    self.layer.borderColor = UIColor(red:0.88, green:0.88, blue:0.88, alpha:1).CGColor
    self.layer.cornerRadius = 5
    self.layer.masksToBounds = true
    self.imageViewContent.frame.size = CGSizeMake(size.width, size.width)
    self.addSubview(self.imageViewContent)

    self.titleLabelContent.frame.size = CGSizeMake(size.width - 20, 30)
    self.titleLabelContent.frame.origin = CGPointMake(10, size.width + 10)
    self.addSubview(self.titleLabelContent)

    descLabelContent.alpha = 0
    descLabelContent.frame.size = CGSizeMake(size.width - 20, size.height - 20)
    descLabelContent.frame.origin = CGPointMake(0, 10)
    self.addSubview(descLabelContent)
}

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

}

加载我的库的视图:

import Foundation
import UIKit

class swipe : UIViewController, KinderDelegate {



@IBOutlet weak var loading: UIActivityIndicatorView!
@IBOutlet weak var loadinglab: UILabel!

var data: Array<KinderModelCard>! = Array()
let controller = KinderViewController()
var backnetwork: NSInteger!

var jsonData: NSDictionary!

//var mutable_pages = NSMutableArray()
var recherche = String()
var category = String()
var zipCode = String()
var price = String()


override func viewDidLoad() {

    //loadingimage.hidden = false
    loading.hidden = false
    loadinglab.hidden = false

    //initialisation de la variable backnetwork
    self.backnetwork = 0



}


func acceptCard(card: KinderModelCard?) {

}

func cancelCard(card: KinderModelCard?) {

}



func fetchData(int: Int, completion: (()->())?) {


    loading.hidden = false
    loadinglab.hidden = false

    NSLog("recherche=%@&categorie=%@&code postal=%@&prix=%@", recherche , category, zipCode, price)



    //Data que l'on envoie en post dans le webservice
    var post:NSString = "recherche=\(recherche)&category=\(category)&zipCode=\(zipCode)&price=\(price)"

    //On remplace les espace par du vide pour la recherche
    var deletespace = post.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, post.length))

    NSLog("Requete: %@",deletespace);



    var url:NSURL = NSURL(string:"http://jdl-barreme-orange.dyndns.org/WEBSERVICE/controllers/controller.objects.php?method=findObject")!


    var postData:NSData = deletespace.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    NSLog("PostData: %@",postLength);

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")


    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)





    if ( urlData != nil ) {

        NSLog("urlData: %ld", urlData!);

        let res = response as! NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {



            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            //On remplace les backslashe par du vide pour l'url de l'image
            var responsestring = responseData.stringByReplacingOccurrencesOfString("\\", withString: "", options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, responseData.length))

            NSLog("Response ==> %@", responsestring);

            var error: NSError?


                            //[jsonData[@"success"] integerValue];

            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary


            let success:NSInteger = jsonData.valueForKey("success") as! NSInteger



            //[jsonData[@"success"] integerValue];

            NSLog("Success: %ld", success);

            if(success == 1)
            {


                if let json = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: nil) as? [String:AnyObject] {
                    for (_, value) in json {
                        if let dict = value as? [String:AnyObject] {
                            let repo = Repository(jsonData: dict)
                            repos.append(repo)
                        }
                    }
                }




                NSLog("Recherche OK");


                loading.hidden = true
                loadinglab.hidden = true

                let newCard = Model()

                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

                for repo in repos {
                    //NSLog("title: %@", repo.title!)
                    println(repo.idobjet)
                    println(repo.title)
                    println(repo.price)
                    println(repo.description)
                    println(repo.added)
                    println(repo.userid)
                    println(repo.user_name)
                    println(repo.user_zipCode)
                    println(repo.category_id)
                    println(repo.category_label)
                    println(repo.subcategory_id)
                    println(repo.subcategory_label)
                    println(repo.picture_url)

                }

                //Construct the imgUrl to get an image URL for the pages
                let urlString: NSString =  repos.picture_url!
                if let url = NSURL(string: urlString as String) {
                    if let data = NSData(contentsOfURL: url) {
                        newCard.image = UIImage(data: data)!

                        newCard.content = appDelegate.titreApp

                        NSLog("le titre est %@", appDelegate.titreApp)

                        newCard.desc = appDelegate.priceApp
                        self.data.append(newCard)
                        NSLog("fetch new data")

                        }
                    }
                }



            else {


                loading.hidden = true
                loadinglab.hidden = true
                //on définit backnetwork à 2 pour reloadCard
                self.backnetwork = 2

                var error_msg:NSString

                //on récupére le message dans le php, avec le champ du JSON "message" et on l'affiche
                if jsonData["message"] as? NSString != nil {
                    error_msg = jsonData["message"] as! NSString
                } else {
                    error_msg = "Erreur inconnue"
                }
                var alertView:UIAlertView = UIAlertView()
                alertView.title = "Recherche échouée"
                alertView.message = error_msg as String
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()

                //On appel la fonction reloadCard qui vas lire 2 à backnetwork et dismiss
                reloadCard()

                return
            }

        }
        else {
            completion!()


            loading.hidden = true
            loadinglab.hidden = true

            var error_msg:NSString

            //on récupére le message dans le php, avec le champ du JSON "message" et on l'affiche
            if jsonData["message"] as? NSString != nil {
                error_msg = jsonData["message"] as! NSString
            } else {
                error_msg = "Erreur inconnue"
            }
            var alertView:UIAlertView = UIAlertView()
            alertView.title = "Recherche échouée"
            alertView.message = error_msg as String
            alertView.delegate = self
            alertView.addButtonWithTitle("OK")
            alertView.show()

            self.dismissViewControllerAnimated(true, completion: nil)
            return
        }
    }
    else {

        completion!()
        //si UrlData est nil, j'incrémente ma variable backnetwork à 1 pour reloadCard
        self.backnetwork = 1
        NSLog("backnetwork DATA : %i", backnetwork)


        loading.hidden = true
        loadinglab.hidden = true

        return

    }


    if self.data.count == 5 {
        completion!()
        return
    }
    else {

        self.fetchData(0, completion: completion)
    }

}


func signalReload() {
    println("call signal")
    data.removeAll(keepCapacity: false)
    self.fetchData(0, completion: { () -> () in
        self.controller.reloadData()

    })


    println("end signl")

}

func reloadCard() -> [KinderModelCard]? {
    NSLog("reload data")

    //Si backnetwork =1 udlData est nil, donc impossible de joindre le serveur, check de la connexion
    if backnetwork == 1 {
        NSLog("backnetwork reload : %i", backnetwork)
        self.dismissViewControllerAnimated(true, completion: nil)

        var alertView:UIAlertView = UIAlertView()
        alertView.title = "Recherche échouée"
        alertView.message = "Vérifiez votre connexion"
        alertView.delegate = self
        alertView.addButtonWithTitle("OK")
        alertView.show()

    }
        //Si backnetwork =2 la recherche n'est pas bonne, provient de
    else if backnetwork == 2 {
        NSLog("backnetwork reload : %i", backnetwork)
        self.dismissViewControllerAnimated(true, completion: nil)

    }


    return data

}

override func viewDidAppear(animated: Bool)
{
    //si backnetwork est égale à 1 alors je dismiss
    if backnetwork == 1 {
        NSLog("backnetwork viewdid : %i", backnetwork)
        self.dismissViewControllerAnimated(true, completion: nil)


    }

    else {
        fetchData(0, completion: { () -> () in
            self.controller.delegate = self
            self.presentViewController(self.controller, animated: true, completion: nil)
        })
    }

}




}    

感谢您阅读我的帖子。

0 个答案:

没有答案