swift中自定义可视化控件

2017-04-07  本文已影响0人  一束强光

前言

自定义控件的时候,经常会不仅在代码中创建该控件,现在还越来越多的在Storyboard和XIB中直接创建,如果仅仅是为了修改某些属性,或者在运行过程中不需要修改的东西,我们就不需要每次都拖线,修改属性。

示例1:按钮的圆角、边框

在可视化创建UI的过程中,总有需要设置按钮的圆角、边框的情况,在最开始,作者都是使用的 1.拖线,2.修改属性。此类方法。
后来发现,可以直接在User Defined Runtime Attributes中添加运行时修改的属性,于是,再也不需要为仅仅做展示用的一些控件拖线来修改layer了。


注:上图中的borderColorFromUIColor和shadowColorFromUIColor用于设置边框颜色和阴影颜色,直接设置是UIColor,但对应的属性是CGColor,所以需要为CALayer添加分类:

#import <QuartzCore/QuartzCore.h>

#import <UIKit/UIKit.h>
@interface CALayer (Addition)

@property(nonatomic, strong) UIColor *borderColorFromUIColor;
@property(nonatomic, strong) UIColor *shadowColorFromUIColor;
- (void)setBorderColorFromUIColor:(UIColor *)color;
- (void)setShadowColorFromUIColor:(UIColor *)color;
@end
#import "CALayer+Addition.h"
#import <objc/runtime.h>

@implementation CALayer (Addition)
//static const void *borderColorFromUIColorKey = &borderColorFromUIColorKey;

//@dynamic borderColorFromUIColor;


- (UIColor *)borderColorFromUIColor {
    return objc_getAssociatedObject(self, @selector(borderColorFromUIColor));
}

-(void)setBorderColorFromUIColor:(UIColor *)color

{
    objc_setAssociatedObject(self, @selector(borderColorFromUIColor), color, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setBorderColorFromUI:self.borderColorFromUIColor];
}

- (void)setBorderColorFromUI:(UIColor *)color

{
    self.borderColor = color.CGColor;
    
}
- (UIColor *)shadowColorFromUIColor {
    return objc_getAssociatedObject(self, @selector(shadowColorFromUIColor));
}

-(void)setShadowColorFromUIColor:(UIColor *)color

{
    objc_setAssociatedObject(self, @selector(shadowColorFromUIColor), color, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setShadowColorFromUI:self.borderColorFromUIColor];
}

- (void)setShadowColorFromUI:(UIColor *)color

{
    self.shadowColor = color.CGColor;
}
@end

但是后来发现,每次都为了添加圆角,复制一大堆Key Path:

import UIKit
//@IBDesignable告诉编译器,此类可以被nib识别使用
@IBDesignable class BoardButton: UIButton {

    //@IBInspectable告诉编译器,这个属性是可视化的
    @IBInspectable var borderWidth : CGFloat = 0{
        didSet{
            layer.borderWidth = borderWidth
        }
    }
    
    @IBInspectable var borderColor : UIColor = UIColor.clear{
        didSet{
            layer.borderColor = borderColor.cgColor
        }
    }
    
    @IBInspectable var cornerRadius : CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
        }
    }
    
    @IBInspectable var masksToBounds : Bool = false{
        didSet{
            layer.masksToBounds = masksToBounds
        }
    }

}

这样直接在XIB文件中添加一个UIButton,并设置好约束,修改类别为BoardButton,就可以看到具体的属性了。

这样是不是很轻松呢,以后可以直接把你写好的按钮拿到新的项目中,就可以直接设置layer的一些属性了,你也可以添加阴影,方法是一样的。

示例2:点击上传图片或照片的view

做好了上面的按钮后,正好需要提取一个上传照片的工具类,我就准备把它集成到一个view上面去,先说说这个view的功能:

import UIKit
import SVProgressHUD
@IBDesignable class AddImageView: UIView ,UIActionSheetDelegate{
    // 成功选择了一张图片
    var didSelectedPicture : ((_ imageUrl: String) -> ())?
    // 选择图片失败
    var failedSelectedPicture : ((_ info: String) -> ())?
    // 选择了删除图片
    var didClickDeletePicture : (() -> ())?
    // 弹出视图的viewController
    var presentViewController : UIViewController? = {
        return UIApplication.shared.keyWindow?.rootViewController
    }()
    //删除照片的模式,false:通过点击图片删除,true:通过删除按钮删除
    @IBInspectable var bgColor : UIColor = UIColor.white {
        didSet {
            backgroundColor = bgColor
        }
    }
    //选择相册的模式,如果都选择FALSE,则都改为TRUE
    @IBInspectable var fromPhoto : Bool = true {
        didSet {
        }
    }
    //选择拍照的模式,如果都选择FALSE,则都改为TRUE
    @IBInspectable var fromCamera : Bool = true {
        didSet {
        }
    }
    //删除照片的模式,false:通过点击图片删除,true:通过删除按钮删除
    @IBInspectable var delbtnBtntype : Bool = false {
        didSet {
        }
    }
    //删除按钮图片
    @IBInspectable var delbtnImage : UIImage? {
        didSet {
        }
    }
    //删除按钮size
    @IBInspectable var delbtnSize : CGSize = CGSize(width: 10, height:10) {
        didSet {
        }
    }
    // 默认背景图片
    @IBInspectable var defaultImage : UIImage?{
        didSet{
            imageView.image = defaultImage
        }
    }
    //默认背景图片的size
    @IBInspectable var defaultImageSize : CGSize = CGSize(width: 10, height:10) {
        didSet {
        }
    }
    //选中的照片
    var selectedImage : UIImage? {
        didSet{
            imageView.contentMode = .scaleAspectFit
            imageView.image = selectedImage
        }
    }
    // 删除按钮
    var deleteButton : UIButton
    // 整个ImageView
    var imageView : UIImageView
    // 图片选择器界面
    var imagePickerController: UIImagePickerController?
    // 代码创建时
    override init(frame: CGRect) {
        imageView = UIImageView()
        deleteButton = UIButton()
        super.init(frame: frame)
        addSubview(imageView)
        addSubview(deleteButton)
        addTapOnImageView()
    }
    // XIB创建时
    required init?(coder aDecoder: NSCoder) {
        imageView = UIImageView()
        deleteButton = UIButton()
        super.init(coder: aDecoder)
        addSubview(imageView)
        addSubview(deleteButton)
        addTapOnImageView()
    }
    func addTapOnImageView() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
    @objc private func tapImageView() {
        if fromPhoto == true && fromCamera == false {
            if selectedImage == nil {//初次选择照片
                addPhonto(type:.photoLibrary)
            }else{
                let alert = UIActionSheet.init(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "重新选择","删除")
                alert.tag = 103
                if presentViewController != nil {
                    alert.show(in: (presentViewController?.view)!)
                }
            }
        }else if fromPhoto == false && fromCamera == true {
            if selectedImage == nil {//初次选择照片
                addPhonto(type:.camera)
            }else{
                let alert = UIActionSheet.init(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "重新拍照","删除")
                alert.tag = 102
                if presentViewController != nil {
                    alert.show(in: (presentViewController?.view)!)
                }
            }
        }else{
            let alert = UIActionSheet.init(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "相册","相机")
            alert.tag = 101
            if presentViewController != nil {
                alert.show(in: (presentViewController?.view)!)
            }
        }
    }
    func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
        if actionSheet.tag == 101 {
            switch buttonIndex {
            case 1:
                addPhonto(type:.photoLibrary)
            case 2:
                addPhonto(type:.camera)
            default: break
            }
        }else if actionSheet.tag == 102 {
            switch buttonIndex {
            case 1:
                addPhonto(type:.camera)
            case 2:
                deletePhoto()
            default: break
            }
        }else if actionSheet.tag == 103 {
            switch buttonIndex {
            case 1:
                addPhonto(type:.photoLibrary)
            case 2:
                 deletePhoto()
            default: break
            }
        }
    }
    func layoutImageViewAndButton() {
        var width_background : CGFloat = 0.0
        var height_background : CGFloat = 0.0
        var y_background : CGFloat = 0.0
        if delbtnBtntype == false{//如果是点击图片的方式删除图片,没有删除按钮
            width_background = width
            height_background = height
            deleteButton.removeFromSuperview()
        }else{//如果是点击删除按钮的方式删除图片
            y_background = delbtnSize.height / CGFloat(2.0)
            width_background = width - delbtnSize.width / 2.0
            height_background = height - delbtnSize.height / 2.0
            deleteButton.frame = CGRect(origin: CGPoint(x: width_background, y: 0), size: delbtnSize)
            deleteButton.addTarget(self, action: #selector(didClickDeleteBtn), for: .touchUpInside)
            deleteButton.setBackgroundImage(delbtnImage, for: .normal)
            backgroundColor = UIColor.white
            let backView = UIView.init(frame: CGRect(x: 0.0, y: y_background, width: width_background, height: height_background))
            backView.backgroundColor = bgColor
            insertSubview(backView, at: 0)
        }
        imageView.frame = CGRect(x: 0.0, y: y_background, width: width_background, height: height_background)
        if selectedImage == nil{//没有选中的图片了,展示默认图
            if defaultImage != nil {//有默认图
                if (defaultImageSize.width) <= width_background && (defaultImageSize.height) <= height_background {//设置的默认图的size比自身size小
                    UIGraphicsBeginImageContextWithOptions(defaultImageSize,false,UIScreen.main.scale)
                    defaultImage?.draw(in: CGRect(x:0, y:0, width:defaultImageSize.width, height:defaultImageSize.height))
                    let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                    UIGraphicsEndImageContext();
                    imageView.contentMode = .center
                    imageView.image = reSizeImage
                }else{
                    imageView.contentMode = .scaleAspectFit
                    imageView.image = defaultImage
                }
            }
        }else{//有选中的图片了,不展示默认图
            imageView.contentMode = .scaleAspectFit
        }
    }
    @objc private func didClickDeleteBtn() {
        deletePhoto()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        layoutImageViewAndButton()
    }
}
extension AddImageView {
    func deletePhoto() {
        selectedImage = nil
        layoutImageViewAndButton()
        if didClickDeletePicture != nil {
            didClickDeletePicture!()
        }
    }
    func upLoadSeletecdImage(image: UIImage) {
        // 上传图片的方法,可以设置到此view中
        NetworkTool.sharedInstance.uploadImage(image: selectedImage!, progressing:{(progress:Double)in
            SVProgressHUD.showProgress(Float(progress))
        },success: { (result, isSuccess) in
            SVProgressHUD.dismiss()
            if isSuccess{
                if let returnUrl = result["body"]["picurl"]["returnUrl"].string {
                    if self.didSelectedPicture != nil{
                        self.didSelectedPicture!(returnUrl)
                    }
                }else{
                    if self.failedSelectedPicture != nil{
                        self.failedSelectedPicture!("上传图片失败")
                    }
                }
            }
            
        }) { (error) in
            SVProgressHUD.dismiss()
        }
    }
}
extension AddImageView: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //MARK:- present选择照片
    func addPhonto(type :UIImagePickerControllerSourceType) {
        if UIImagePickerController.isSourceTypeAvailable(type) == false {
            if failedSelectedPicture != nil {
                failedSelectedPicture!("该设备不支持相机")
            }
            return
        }
        imagePickerController = UIImagePickerController()
        imagePickerController?.delegate = self
        imagePickerController?.sourceType = type
        imagePickerController?.allowsEditing = true
        // 打开图片选择器
        presentViewController?.present(imagePickerController!, animated: true, completion: nil)
    }
    //MARK: 返回照片信息
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        presentViewController?.dismiss(animated: true, completion: nil)
        selectedImage = info[UIImagePickerControllerEditedImage] as? UIImage
        if selectedImage != nil{
            upLoadSeletecdImage(image: selectedImage!)
        }
        if failedSelectedPicture != nil && selectedImage == nil {
            failedSelectedPicture!("未获取到图片信息")
        }
    }
}
AddimageView属性

具体内容稍后会放在GitHub并不断优化,欢迎下载尝试。

上一篇下一篇

猜你喜欢

热点阅读