Swift5 踩过的坑和奇怪的API笔记

Posted 时光不染

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift5 踩过的坑和奇怪的API笔记相关的知识,希望对你有一定的参考价值。

踩过的坑和奇怪的API笔记

UINavigationController 导航栏

设置导航栏颜色
	navigationController?.navigationBar.barTintColor =  .blue
去掉导航栏下面的分割线
	navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
	navigationController?.navigationBar.shadowImage = UIImage()
  • 此时导航栏颜色和View背景相同,应该类似吧导航栏设置透明了的效果
  • 使用方法一设置导航栏颜色为.clear 并不能达到相同效果
  • 本方法会导致方法一设置导航栏颜色失效,此时使用以下代码设置导航栏颜色
	navigationController?.navigationBar.backgroundColor = .orange
设置导航栏字体和字体颜色
	self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black,NSAttributedString.Key.font : UIFont.systemFont(ofSize: 25)]

 
 

UITabBar

UITabBar和导航栏结合使用
	tabBarCtrl = UITabBarController()
    tabBarCtrl.tabBar.tintColor = .DesignGreen
    let view1 = ViewHome()
    view1.tabBarItem.image = UIImage(named: "xiaozujian")
    view1.tabBarItem.title = "组件"   
    let view2 = ViewIcon()
    view2.tabBarItem.image = UIImage(named: "tubiao")
    view2.tabBarItem.title = "图标"

    let view1 = UINavigationController.init(rootViewController: viewHome)
    let view2 = UINavigationController.init(rootViewController: viewIcon)
    tabBarCtrl.addChild(view1)
    tabBarCtrl.addChild(view2)
    tabBarCtrl.selectedIndex = 0 //默认选择
    self.window?.rootViewController = tabBarCtrl
    window?.makeKeyAndVisible()
获取UITabBar的高度
let height = tabBarCtrl.tabBar.bounds.size.height
跳转界面隐藏UITabBar的方案
	override func viewWillDisappear(_ animated: Bool) 
        tabBarCtrl.tabBar.isHidden = true
    

 
 

UITableView

UITableViewCell里点击事件不生效

使用 cell.contentView.addSubview 代替 cell.addSubview

设置分割线内边距
	tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
隐藏所有分割线分割线
  • 方法一:
	self.separatorStyle = .none
  • 方法二:
	tableView.separatorInset = UIEdgeInsets(top: 0, left: tableView.frame.width, bottom: 0, right: 0)
隐藏底部多余行及分割线
	tableview.tableFooterView = UIView(frame: CGRect.zero)

 
 

UICollectionView & UIScrollView

cell里的按钮区域只能点击无法滑动
使用`UILabel`或`UIImageView`等绑定`UITapGestureRecognizer`  代替`UIButton`
	func InitUI()
		let img = UIImageView(frame:CGRect(xxxxxx))
	    let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ClickBtn(_:)))
	    img.addGestureRecognizer(singleTapGesture)
	    img.isUserInteractionEnabled = true
    
	@objc func ClickBtn(_ tap:UITapGestureRecognizer)
        
    
允许多选
 	collection.allowsMultipleSelection = true
ScrollView是否显示滑动条
	scrollView.showsHorizontalScrollIndicator = false
	scrollView.showsVerticalScrollIndicator = false
ScrollView使ContentSize小于UIScrollView大小也能滑动
   scrollView.alwaysBounceVertical = true
   scrollView.alwaysBounceHorizontal = true
ScrollView分页滑动
	func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) 
        if (!decelerate)
        
            scrollView.setContentOffset(CGPoint(x: CGFloat(Int(scrollView.contentOffset.x/pageWidth + 0.5))*pageWidth, y: scrollView.contentOffset.y), animated: true)
            selectPage = Int(scrollView.contentOffset.x/pageWidth + 0.5)
        
    
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) 
        scrollView.setContentOffset(CGPoint(x: CGFloat(Int(scrollView.contentOffset.x/pageWidth + 0.5))*pageWidth, y: scrollView.contentOffset.y), animated: true)
        selectPage = Int(scrollView.contentOffset.x/pageWidth + 0.5)
    
UIScrollView截长图
///截长图
	extension UIScrollView 
    /// 截长屏Image
    var captureLongImage: UIImage? 
        
        var image: UIImage? = nil
        let savedContentOffset:CGPoint? = contentOffset
        let savedFrame:CGRect? = frame
        
        contentOffset = .zero
        frame = CGRect(x: 0, y: 0,
                       width: contentSize.width,
                       height: contentSize.height)
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: frame.size.width,
                   height: frame.size.height),
            false,
            0.0)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        
        contentOffset = savedContentOffset ?? contentOffset
        frame = savedFrame ?? frame
        return image
        
    
    
    fileprivate func writeImageToAlbum(_ image: UIImage) 
            
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    
        
    @objc fileprivate func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) 
            if let _ = error as NSError? 
                print("保存失败,请重试")
             else 
                print("保存成功!")
            
    
    

UIView

截图
	extension UIView 
    /// 截屏Image
    	func captureImage(size:CGSize)-> UIImage? 
        
	        // 参数①:截屏区域  参数②:是否透明  参数③:清晰度
	        UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0)
	        layer.render(in: UIGraphicsGetCurrentContext()!)
	        let image = UIGraphicsGetImageFromCurrentImageContext()
	        
	        UIGraphicsEndImageContext()
	        return image
	    
	    
	     func captureImageInPos( rect: CGRect) -> UIImage? 
	      UIGraphicsBeginImageContext(rect.size)
	      guard let context = UIGraphicsGetCurrentContext() else  return nil 
	      context.translateBy(x: -rect.minX, y: -rect.minY)
	        self.draw(.zero)
	      let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
	      UIGraphicsEndImageContext()
	      return croppedImage
    	
	
拼接图片
	//拼接图片
	func combinTwoImage(image1:UIImage,image2:UIImage) -> UIImage
	
	    let width = max(image1.size.width, image2.size.width)
	    let height = image1.size.height + image2.size.height
	    let offScreenSize = CGSize.init(width: width, height: height)
	    
	    
	    UIGraphicsBeginImageContextWithOptions(offScreenSize, false, 0.0)
	    let rect = CGRect.init(x:0, y:0, width:width, height:image1.size.height)
	    image1.draw(in: rect)
	    
	    let rect2 = CGRect.init(x:0, y:image1.size.height, width:width, height:image2.size.height)
	    image2.draw(in: rect2)
	    
	    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
	    
	    UIGraphicsEndImageContext();
	    
	    return image;
	
获取当前UIView的UIVIewController
	extension UIView
		func ParentCtrl()->UIViewController
	       var vc:UIResponder = self
	       while vc.isKind(of: UIViewController.self) != true 
	           vc = vc.next!
	       
	       return vc as! UIViewController
		
	

 
 

UIImage

重设图片大小和等比例缩放
	extension UIImage 
	    /**
	     *  重设图片大小
	     */
	    func  reSizeImage(reSize: CGSize )-> UIImage  
	        //UIGraphicsBeginImageContext(reSize);
	        UIGraphicsBeginImageContextWithOptions (reSize, false , UIScreen .main.scale);
	        //绘制图片
	        self.draw(in: CGRect(x: 0,
	                              y: 0,
	                              width: reSize.width,
	                              height: reSize.height))
	        let  reSizeImage: UIImage  =  UIGraphicsGetImageFromCurrentImageContext ()!
	        UIGraphicsEndImageContext ();
	        return  reSizeImage;
	    
	    
	    /**
	     *  等比率缩放
	     */
	    func  scaleImage(scaleSize: CGFloat )-> UIImage  
	        let  reSize = CGSize(width: self .size.width * scaleSize, height: self .size.height * scaleSize)  
	        return  reSizeImage(reSize: reSize)
	    
    
裁切图片
	extension UIImage
	    func crop(_ rect: CGRect) -> UIImage? 
	        let img = self.reSizeImage(reSize: UIScreen.main.currentMode!.size)
	        var newRect = rect
	        let WIDTH:CGFloat = UIScreen.main.bounds.width
			let RELWIDTH = UIScreen.main.currentMode?.size.width

	        let scale = (RELWIDTH!/WIDTH)
	        newRect.origin.x *=  scale*scale
	        newRect.origin.y *= scale*scale
	        newRect.size.width *= scale*scale
	        newRect.size.height *= scale*scale
	        
	        guard let imageRef = img.cgImage?.cropping(to: newRect) else  return nil 
	        return UIImage(cgImage: imageRef)
	    
	
获取纯色UIImage
	extension UIImage 
	    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) 
	        let rect = CGRect(origin: .zero, size: size)
	        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
	        color.setFill()
	        UIRectFill(rect)
	        let image = UIGraphicsGetImageFromCurrentImageContext()
	        UIGraphicsEndImageContext()
	
	        guard let cgImage = image?.cgImage else  return nil 
	        self.init(cgImage: cgImage)
	    
	
改变颜色
	extension UIImage 
		func changeColor(color:UIColor) -> UIImage 
		           UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
		           let context = UIGraphicsGetCurrentContext()
		           context?.translateBy(x: 0, y: self.size.height)
		           context?.scaleBy(x: 1.0, y: -1.0)//kCGBlendModeNormal
		           context?.setBlendMode(.normal)
		           let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
		           context?.clip(to: rect, mask: self.cgImage!);
		           color.setFill()
		           context?.fill(rect)
		           let newImage = UIGraphicsGetImageFromCurrentImageContext()
		           UIGraphicsEndImageContext()
		           return newImage!
		       
       
获取网络图片
	func GetImgByUrl(path:String)->UIImage
	    
	    let url = NSURL(string: path)!
	
	    let data = NSData(contentsOf: url as URL)!
	
	    return UIImage(data: data as Data,scale: 1.0)!
	

 
 

UIImageView

圆角不生效
	imgView.layer.masksToBounds = true

 
 

UIButton

UIButton中图片和文字的位置变换
	enum ButtonEdgeInsetsStyle 
	   case ButtonEdgeInsetsStyleTop // image在上,label在下
	   case ButtonEdgeInsetsStyleLeft  // image在左,label在右
	   case ButtonEdgeInsetsStyleBottom  // image在下,label在上
	   case ButtonEdgeInsetsStyleRight // image在右,label在左
	
	extension UIButton 
	    func layoutButtonEdgeInsets(style:ButtonEdgeInsetsStyle,space:CGFloat) 
	        let labelWidth : CGFloat = self.titleLabel?.frame.size.height ?? 36
	        let labelHeight : CGFloat = self.titleLabel?.frame.size.width ?? 20
	        var imageEdgeInset =以上是关于Swift5 踩过的坑和奇怪的API笔记的主要内容,如果未能解决你的问题,请参考以下文章

Swift5 踩过的坑和奇怪的API笔记

程序员架构修炼:踩过的坑和经验总结故障复盘流程及模板

[转] 那些在使用webpack时踩过的坑

HttpClient笔记与踩过的坑

Activity生命周期,学习笔记(踩过的坑)

记录Android Studio连接华为(nova)手机鸿蒙系统踩过的坑