Swift封装的友盟分享,可以直接拿来用的

分享这个功能基本每个APP都会有,我今天给大家分享一款我自己封装好的,代码的话,我会加到文章最后可以去下载,比较简单,先上个效果图吧:


Swift封装的友盟分享,可以直接拿来用的_第1张图片
友盟分享3.gif

这个代码主要都在ShareView.swift文件里,比较简单,我觉得效果挺实用的,不想动手的朋友,可以直接拿着撸。

下面我就一步一步说说怎么实现的:

第一步确定你要分享给别人什么玩意,无非就是图片,文字内容,标题,URL吧,我们来定义几个属性

    private var shareContent:String!
    private var shareImage:UIImage!
    private var shareUrl:String!
    private var shareTitle:String!

这里我直接用private来修饰了,作为一个准全栈工程师,这点严谨性还是得有的,接着我大致来说说我的思路吧,我准备先添加个灰色视图(bgView)当遮罩背景,然后在添加一个充当容器的视图(contentView)在它上面做些文章,当然ShareView是要集成自UIView的,毕竟封装的东西越简单越好,别人一看就能懂,自己也得劲。(适当装逼,有益健康)

我准备在这个contentView上面添加一个可以左右滑动的UIScollView,中间是个UIPageControl,下面直接搞个UIButton,基本控件就这么多

    private var bgView:UIView!
    private var contentView:UIView!
    private var rootVC:UIViewController!
    private var scrollView:UIScrollView!
    private var pageControl:UIPageControl!

有人会有疑惑rootVC是个什么鬼,关于这个咱们得往大东家友盟看了,人家有个参数专门让你传的,你不传不行啊是吧,接着往下看。这里为了表达出我优雅的封装,代码的可扩展性,我依然决断的把contentView的高度当成个属性拿出来了,你可以随意写高度,绝对不定死。

private var contentHeight:CGFloat = 220

不闲扯了,下面上代码:

初始化布局,都在这里了

    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加一个遮罩视图
        self.bgView = UIView.init(frame: self.bounds)
        self.bgView.backgroundColor = UIColor.blackColor()
        self.bgView.alpha = 0.0
        self.addSubview(self.bgView)
       
        //给遮罩添加一个手势,用来隐藏视图并移除
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(self.bgViewTapped))
        self.bgView.addGestureRecognizer(tapGesture)
        //这个是容器视图,上面的有scrollView、pageControl、cancelBtn三个子视图
        self.contentView = UIView.init(frame: CGRectMake(0, CGRectGetHeight(frame), CGRectGetWidth(frame), contentHeight))
        self.contentView.backgroundColor = UIColor.groupTableViewBackgroundColor()
        self.addSubview(self.contentView)
        //数组里面是两个数组,第一个数组管图片文件名,第二个管标题名
        let sharePaltformArray = [
            [ "share_weixin", "share_friend", "share_sina" , "share_qq", "share_zone"],
            [ "微信","朋友圈", "微博", "QQ", "QQ空间"]
        ]
        //添加一个可以左右滑动的视图
        self.scrollView = UIScrollView.init(frame: CGRectMake(0, 0, CGRectGetWidth(frame), 130))
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.showsVerticalScrollIndicator = false
        self.scrollView.pagingEnabled = true
        self.scrollView.delegate = self
        self.scrollView.backgroundColor = UIColor.whiteColor()
        self.scrollView.contentOffset = CGPointMake(0, 0)
        self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(frame) * CGFloat(self.pageNum(sharePaltformArray[0].count)), 0)
        self.contentView.addSubview(self.scrollView)
        
        //这个是显示UIScrollView到哪一页的小按钮
        self.pageControl = UIPageControl.init(frame: CGRectMake(0, CGRectGetHeight(self.scrollView.frame), CGRectGetWidth(frame), 35))
        self.pageControl.backgroundColor = UIColor.whiteColor()
        self.pageControl.currentPageIndicatorTintColor = UIColor.grayColor()
        self.pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
        self.pageControl.numberOfPages = pageNum(sharePaltformArray[0].count)
        self.contentView.addSubview(self.pageControl)
        //下面这一大坨全是将的怎么在scrollView上布局小图标
        let buttonWidth:CGFloat = 55.0
        let buttonGap = ( CGRectGetWidth(frame) - buttonWidth * 4 ) / 5
        
        for i in 0 ..< 5 {
            
            let shareButton = UIButton(type:.Custom)
        
            let btnRect = CGRectMake(buttonGap * ( CGFloat(i) + 1) + buttonWidth * CGFloat(i) + (i % 4 == 0 && i != 0 ? 20 : 0), 40, buttonWidth, buttonWidth)
            
            shareButton.frame = btnRect
            shareButton.tag = 100 + i
            shareButton.addTarget(self, action: #selector(self.shareButtonClicked(_:)), forControlEvents: .TouchUpInside)
            shareButton.setBackgroundImage(UIImage(named: sharePaltformArray[0][i]), forState: .Normal)
            shareButton.setBackgroundImage(UIImage(named: sharePaltformArray[0][i] + "_hover"), forState: .Highlighted)
            shareButton.layer.cornerRadius = buttonWidth / 2
            shareButton.layer.masksToBounds = true
            self.scrollView.addSubview(shareButton)
            
            let shareLabel = UILabel.init(frame: CGRectMake(CGRectGetMinX(shareButton.frame), CGRectGetMaxY(shareButton.frame) + 10 , CGRectGetWidth(shareButton.frame), 15))
            shareLabel.font = UIFont.systemFontOfSize(13)
            shareLabel.textColor = UIColor.init(red: 0.24, green: 0.24, blue: 0.25, alpha: 1.0)
            shareLabel.textAlignment = .Center
            shareLabel.text = sharePaltformArray[1][i]
            self.scrollView.addSubview(shareLabel)
        }
        //最后就是添加个取消按钮了
        let cancelBtn = UIButton(type:.Custom)
        cancelBtn.frame = CGRectMake(0, CGRectGetHeight(self.contentView.frame) - 44, CGRectGetWidth(self.contentView.frame), 44)
        cancelBtn.backgroundColor = UIColor.whiteColor()
        cancelBtn.setTitle("取消", forState: .Normal)
        cancelBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        cancelBtn.titleLabel?.font = UIFont.systemFontOfSize(16)
        cancelBtn.addTarget(self, action: #selector(self.cancelBtnClicked), forControlEvents: .TouchUpInside)
        self.contentView.addSubview(cancelBtn)
    }

然后对外写个方法,用来把图片,内容,标题,url这些乱七八糟的东西全传进来

func setShareModel(content:String , image:UIImage , url:String , title:String) {
        
        self.shareContent = content
        self.shareImage = image
        self.shareUrl = url
        self.shareTitle = title
        
    }

下面是取消按钮和遮罩视图的轻拍手势响应的事件

/**
     遮罩背景响应事件
     */
    func bgViewTapped() {
        
        self.dismiss()
        
    }
    
    /**
     取消按钮响应事件
     */
    func cancelBtnClicked() {
        
        self.dismiss()
        
    }

现在来撸一下,这个移除视图的操作是这么玩的

private func dismiss(){
        UIView.animateWithDuration(0.3, animations: { 
                self.bgView.alpha = 0.0
                self.contentView.frame = CGRectMake(0, CGRectGetHeight(self.frame), CGRectGetWidth(self.frame), self.contentHeight)
            
            }) { (finished) in
                self.removeFromSuperview()
        }
        
        
    }

还有就是点击分享按钮要实现跳转APP分享的功能了,差点忘了自己在干啥,要不还是直接看代码吧

    /**
     分享按钮响应事件
     */
    func shareButtonClicked(sender:UIButton) {
        
        let snsTypes:Array!
        var currentShareType:String!
        if sender.tag == 100 {
            snsTypes = [UMShareToWechatSession]
            currentShareType = "1"
            
            UMSocialData.defaultData().extConfig.wechatSessionData.title = self.shareTitle
            UMSocialData.defaultData().extConfig.wechatSessionData.url = self.shareUrl
            
        }else if sender.tag == 100 + 1 {
            snsTypes = [UMShareToWechatTimeline]
            currentShareType = "0"
            if self.shareTitle != nil && self.shareTitle.characters.count > 0 {
                UMSocialData.defaultData().extConfig.wechatTimelineData.title = self.shareTitle
                
            }else{
                UMSocialData.defaultData().extConfig.wechatTimelineData.title = self.shareContent
            }
        }else if sender.tag == 100 + 2 {
            snsTypes = [UMShareToSina]
            currentShareType = "2"
            
            self.shareContent = self.shareUrl + self.shareContent
            
            guard self.shareTitle.characters.count > 0 else{
                UMSocialData.defaultData().extConfig.qzoneData.title = "  "
                return
            }
            UMSocialData.defaultData().extConfig.qzoneData.title = self.shareTitle
            UMSocialData.defaultData().extConfig.qzoneData.url = self.shareUrl
        }else if sender.tag == 100 + 3 {
            snsTypes = [UMShareToQQ]
            currentShareType = "4"
            guard self.shareTitle.characters.count > 0 else{
                UMSocialData.defaultData().extConfig.qqData.title = "  "
                return
            }
            UMSocialData.defaultData().extConfig.qqData.title = self.shareTitle
            UMSocialData.defaultData().extConfig.qqData.url = self.shareUrl
        }else if sender.tag == 100 + 4 {
            snsTypes = [UMShareToQzone]
            currentShareType = "3"
            guard self.shareTitle.characters.count > 0 else{
                UMSocialData.defaultData().extConfig.qzoneData.title = "  "
                return
            }
            UMSocialData.defaultData().extConfig.qzoneData.title = self.shareTitle
            UMSocialData.defaultData().extConfig.qzoneData.url = self.shareUrl
        }else{
            snsTypes = []
            currentShareType = " "
        }
        UMSocialDataService.defaultDataService().postSNSWithTypes(snsTypes, content: self.shareContent, image: self.shareImage, location: nil, urlResource: UMSocialUrlResource.init(snsResourceType: UMSocialUrlResourceTypeDefault, url: self.shareUrl), presentedController: self.rootVC) { (shareResponse) in
            if shareResponse.responseCode == UMSResponseCodeSuccess {
                print("分享成功")
                dispatch_async(dispatch_get_main_queue(), { 
                    
                })
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3)), dispatch_get_main_queue(), {
            self.dismiss()
        })
    }

基本实现的代码就是这些,下面我们要把它这个ShareView加在ViewController上来显示出来
首先定义一个方法

    private func showInView(parentView:UIView) {
        
        parentView.addSubview(self)
        UIView.animateWithDuration(0.3) {
            self.bgView.alpha = 0.4
            self.contentView.frame = CGRectMake(0, CGRectGetHeight(self.frame) - self.contentHeight, CGRectGetWidth(self.frame), self.contentHeight)
        }
        
    }

然后在外面调用下面这个方法来把视图添加上去

func showInViewController(viewController:UIViewController){
        self.rootVC = viewController
        self.showInView(viewController.view)
    }

主要方法就是这些,下面我贴出来别的辅助方法:

//根据意思,我们知道这个方法是根据传入的个人,来判断需要几页显示的
//打比方,我要分享的平台只有三个(QQ,微信,微博),那我一页就能显示完,返回的值就是1,表示一页
private func pageNum(num:Int) -> Int {
        return (num % 4 == 0 ? 0 : 1) + num / 4
    }

 //MARK: - UIScrollViewDelegate
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let pageWidth = CGRectGetWidth(self.bounds)
        let pageFraction = self.scrollView.contentOffset.x / pageWidth
        self.pageControl.currentPage = Int(pageFraction)
        
    }

然后,下面就是最最重要的方法调用了,本来以为写完了,要关电脑睡觉了-_-!!

let shareView = ShareView.init(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
shareView.setShareModel("我是分享的主要内容,我先强调一下,这里我最帅", image: UIImage(named: "share_logo")!, url: "http://www.wufeiyue.com", title: "我是标题,URL是对的")

//你可以这样用:
shareView.showInViewController(self.navigationController)          

//你也可以这样用:
let tabBarVC = appDelegate.window?.rootViewController
shareView.showInViewController(tabBarVC!)

//你同样可以这样用:
shareView.showInViewController(SharedApp.tabbarController)

//这么多种选择,总有一样适合你,选其一

下面是demo地址
https://github.com/eppeo/ShareViewTest

你可能感兴趣的:(Swift封装的友盟分享,可以直接拿来用的)