Swift 基础控件

UIImageView、UITableView、UICollectionView、UIButton、导航栏、UIView

UIImageView -###

1.图片类UIImage

//通过图片名称创建UIImage实例
let image = UIImage(named: "imageName")
//通过文件路径创建UIImage实例
let image = UIImage(contentsOfFile: "filePath")
//通过Data数据创建UIImage实例
let image = UIImage(data: Data())

2.使用UIImageView展示图片

let imageView = UIImageView(frame: CGRectMake(10.0, 10.0, 100.0, 100.0))
let image = UIImage(named: "imageName")
imageView.image = image
self.view.addSubview(imageView)

3.使用UIImageView播放动画

//创建一个图片数组
var images:Array<UIImage> = []
for i in 0 ..< 17 {
   let image = UIImage(named: "qq\(i)")
   images.append(image!)
}
let imageView = UIImageView(frame: self.view.frame)
//设置图像视图的动画图片属性
imageView.animationImages = images
//设置帧动画的时长为五秒
imageView.animationDuration = 1.6
//设置动画循环次数,0为无限播放
imageView.animationRepeatCount = 1
//开始动画的播放
imageView.startAnimating()
self.view.addSubview(imageView)
UITableView -###

1.懒加载

lazy var catalogue : UITableView = {
   let catalogue = UITableView()
   catalogue.delegate = self;
   catalogue.dataSource = self;
   catalogue.tableFooterView = UIView(frame:CGRect.zero)//除去多余的cell
   catalogue.autoresizingMask = .flexibleWidth
   catalogue.register(UITableViewCell.self, forCellReuseIdentifier: "NationalityListView")//非xib cell 注册
   catalogue.register(UINib(nibName: "CatalogueTableViewCell", bundle: nil), forCellReuseIdentifier: "CatalogueTableViewCell")//xib cell 注册
   //分割线样式
   catalogue.separatorInset = UIEdgeInsets.zero;
   catalogue.layoutMargins = UIEdgeInsets.zero;
   ///索引需要的设置
   // 设置索引值颜色
   catalogue.sectionIndexColor = UIColor.gray
   // 设置选中时的索引背景颜色
   catalogue.sectionIndexTrackingBackgroundColor = UIColor.colorWithHex(hexColor: 0xf2f2f2)
   // 设置索引的背景颜色
   catalogue.sectionIndexBackgroundColor = UIColor.colorWithHex(hexColor: 0xf2f2f2)
   
   return catalogue
}()

2.TableView cell 注册/使用

//xib
self.tableView.register(UINib(nibName:"SystemSettingCell", bundle:nil),
       forCellReuseIdentifier:"SystemSettingCell")//注册
let cell = tableView.dequeueReusableCell(withIdentifier: "SystemSettingCell", for: indexPath) as! SystemSettingCell//使用

//不重用 cell数量多,消耗内存严重
let docData = self.doclist[self.typeList[indexPath.section]]![indexPath.row]
let identifier = "\(docData.docPath)\(indexPath.row)"
self.tableView!.register(UINib(nibName:"didDownloadCell", bundle:nil),
                        forCellReuseIdentifier:identifier)
let cell = tableView.dequeueReusableCell(withIdentifier:identifier)
as! didDownloadCell

//非xib
self.tableView.register(noticeTableViewCell.self, forCellReuseIdentifier: "SwiftCell")//注册
let cell:noticeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "SwiftCell") as! noticeTableViewCell//使用

3.原生实现TableView索引

  • 实现后tableview与父视图间会出现间距 用以显示索引
//实现索引数据源代理方法
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return adHeaders
}
//点击索引,移动TableView的组位置
func tableView(_ tableView: UITableView,
                   sectionForSectionIndexTitle title: String, at index: Int) -> Int {
    var tpIndex:Int = 0
        //遍历索引值
        for character in titleData{
            //判断索引值和组名称相等,返回组坐标
            if character == title{
                return tpIndex
            }
            tpIndex += 1
        }
    return 0
}

4.TableViewCell 左滑操作

  • 单个操作按钮
//在这里修改删除按钮的文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "移除"
}
//点击删除按钮的响应方法
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "提示",
                                            message:"是否删除?", preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
    let okAction = UIAlertAction(title: "确定", style: .default, handler: {
        action in
        self.deleteStu(indexPath)
    })
    alertController.addAction(cancelAction)
    alertController.addAction(okAction)
    self.present(alertController, animated: true, completion: nil)
}
func deleteStu(_ indexPath:IndexPath){
}
  • 多个操作按钮
@available(iOS 11.0, *)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .normal, title: "") { [weak self] (action, view, resultClosure) in
        guard self != nil else {
            return
        }
        // TODO
    }
    let shareAction = UIContextualAction(style: .normal, title: "") { [weak self] (action, view, resultClosure) in
        guard self != nil else {
            return
        }
        // TODO
    }
    deleteAction.backgroundColor = .red
    shareAction.backgroundColor = .yellow
    let actions = UISwipeActionsConfiguration(actions: [deleteAction, shareAction])
    actions.performsFirstActionWithFullSwipe = false; // 禁止侧滑到最左边触发删除或者分享回调事件
    return actions
}
//  适配iOS 11.0之后 修改侧滑删除、分享按钮
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
    if #available(iOS 11.0, *) {
        for subView in tableView.subviews {
            if NSStringFromClass(subView.classForCoder) == "UISwipeActionPullView" {
                
                if let deleteBtn: UIButton = subView.subviews.last as? UIButton  {
                    changeAction(sourceBtn: deleteBtn, title: "取消收藏", imageStr: "icon_collecton_delete")
                }
                if let shareBtn: UIButton = subView.subviews.first as? UIButton  {
                    changeAction(sourceBtn: shareBtn, title: "分享", imageStr: "icon_collecton_share")
                }
                
            }else if NSStringFromClass(subView.classForCoder) == "_UITableViewCellSwipeContainerView" {
                
                // iOS13.0之后
                for sub in subView.subviews {
                    if NSStringFromClass(sub.classForCoder) == "UISwipeActionPullView" {
                        if let deleteBtn: UIButton = sub.subviews.last as? UIButton  {
                            changeAction(sourceBtn: deleteBtn, title: "取消收藏", imageStr: "icon_collecton_delete")
                        }
                        if let shareBtn: UIButton = sub.subviews.first as? UIButton  {
                            changeAction(sourceBtn: shareBtn, title: "分享", imageStr: "icon_collecton_share")
                        }
                    }
                }
                
            }
        }
    }
}
func changeAction(sourceBtn: UIButton, title: String?, imageStr: String?) {
    let btn = UIButton(type: .custom)
    btn.frame = CGRect(x: 0, y: 0, width: sourceBtn.frame.width, height: sourceBtn.frame.height)
    btn.backgroundColor = sourceBtn.backgroundColor
    btn.setImage(UIImage(named: imageStr ?? ""), for: .normal)
    btn.setTitle(title, for: .normal)
    btn.setTitleColor(UIColor.white, for: .normal)
    btn.titleLabel?.font = UIFont.init(name: "PingFang-SC-Medium", size: 14)
    if #available(iOS 13.0, *) {
        btn.titleLabel?.font = UIFont.init(name: "PingFang-SC-Medium", size: 13)
    } else {
        btn.contentHorizontalAlignment = .left
    }
  // 修改button的图文上下显示
    btn.Jzz_setButtonStyle(buttonMode: .Top, spacing: 1)
    btn.isUserInteractionEnabled = false
    sourceBtn.backgroundColor = .clear
    sourceBtn.addSubview(btn)
}
UICollectionView -###

1.懒加载

private lazy var collectionView: UICollectionView = {
   let layout = UICollectionViewFlowLayout()
   layout.itemSize = bounds.size
   //滚动方向
   layout.scrollDirection = .horizontal
   // 1.设置 最小行间距
   layout.minimumLineSpacing = 20;
   // 2.设置 最小列间距
   layout. minimumInteritemSpacing  = 10;
   // 3.设置item块的大小 (可以用于自适应)
   layout.estimatedItemSize = CGSizeMake(20, 60);
   //item内边距
   layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
   
   let collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
   collectionView.backgroundColor = .clear
   //不显示滚动条
   collectionView.showsHorizontalScrollIndicator = false
   collectionView.showsVerticalScrollIndicator = false
   //类似分页效果
   collectionView.isPagingEnabled = true
   collectionView.delegate = self
   collectionView.dataSource = self
   collectionView.register(ICycleViewCell.self, forCellWithReuseIdentifier: ICycleViewConst.cellIdentifier)//非 xib cell 注册
   collectionView.register(UINib.init(nibName: "moocHeadImgCell", bundle: Bundle.main), forCellWithReuseIdentifier: "moocHeadImgCell")// xib cell 注册
   //注册头尾视图
   collectView.register(SwiftFooterCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SwiftFooterCollectionReusableView")//非 xib cell 注册
   collectionStuAnswer.register(UINib.init(nibName: "stuAnswerSectionHeader", bundle: Bundle.main), forSupplementaryViewOfKind:
           UICollectionElementKindSectionHeader, withReuseIdentifier: "stuAnswerSectionHeader")xib cell 注册
   return collectionView
}()

2.UICollectionViewCell 注册使用

//xib
self.collectionView.register(UINib.init(nibName: "ZQUICollectionViewCell_Img", bundle: nil), forCellWithReuseIdentifier: "ZQUICollectionViewCell_Img")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ZQUICollectionViewCell_Img", for: indexPath) as! ZQUICollectionViewCell_Img
//非xib
collectionView.register(TalnetImageShareCell.self, forCellWithReuseIdentifier: "cell")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
for: indexPath) as! TalnetImageShareCell

3.UICollectionView 头尾视图

//设置 区头和区尾 
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
   if kind == UICollectionView.elementKindSectionHeader  {
       let headerView:SwiftHeaderCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SwiftHeaderCollectionReusableView", for: indexPath) as! SwiftHeaderCollectionReusableView
       return headerView
   }else{
       let footerView:SwiftFooterCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SwiftFooterCollectionReusableView", for: indexPath) as! SwiftFooterCollectionReusableView
       return footerView
   }
}
UIButton-###

1.文字和图片共存

  • 添加category,UIButton + Extension
enum JZZButtonMode {
   case Top
   case Bottom
   case Left
   case Right
}
import UIKit

extension UIButton {

   /// 快速调整图片与文字位置
   ///
   /// - Parameters:
   ///   - buttonMode: 图片所在位置
   ///   - spacing: 文字和图片之间的间距
   func Jzz_setButtonStyle(buttonMode: JZZButtonMode,
                                            spacing: CGFloat) {
       let imageSize = self.imageRect(forContentRect: self.frame)
       let titleFont = self.titleLabel?.font!
       let titleSize = titleLabel?.text?.size(withAttributes: [kCTFontAttributeName as NSAttributedString.Key: titleFont!]) ?? CGSize.zero
       var titleInsets: UIEdgeInsets
       var imageInsets: UIEdgeInsets
       switch (buttonMode){
       case .Top:
           titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing)/2,
                                      left: -(imageSize.width), bottom: 0, right: 0)
           imageInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing)/2, left: 0, bottom: 0, right: -titleSize.width)
       case .Bottom:
           titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing)/2,
                                      left: -(imageSize.width), bottom: 0, right: 0)
           imageInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing)/2, left: 0, bottom: 0, right: -titleSize.width)
       case .Left:
           titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
           imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
       case .Right:
           titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
           imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
                                      right: -(titleSize.width * 2 + spacing))
       }
       self.titleEdgeInsets = titleInsets
       self.imageEdgeInsets = imageInsets
   }
}
  • 按钮显示页面
import UIKit

class ButtonStyleViewControllerTwo: BaseViewController {

   @IBOutlet var btn1: UIButton!
   @IBOutlet var btn2: UIButton!
   @IBOutlet var btn3: UIButton!
   @IBOutlet var btn4: UIButton!

   override func viewDidLoad() {
       super.viewDidLoad()
       btn1.Jzz_setButtonStyle(buttonMode: .Top, spacing: 10)
       btn2.Jzz_setButtonStyle(buttonMode: .Left, spacing: 10)
       btn3.Jzz_setButtonStyle(buttonMode: .Right, spacing: 10)
       btn4.Jzz_setButtonStyle(buttonMode: .Bottom, spacing: 10)
       // Do any additional setup after loading the view.
   }

   /*
   // MARK: - Navigation
   // In a storyboard-based application, you will often want to do a little preparation before navigation
   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       // Get the new view controller using segue.destination.
       // Pass the selected object to the new view controller.
   }
   */
}
  • 效果


    扩展Button按钮样式.png

2.按钮懒加载,按钮样式

lazy var btn_submit : UIButton = {
       let btn = UIButton()
       btn.setTitle("提 交", for: .normal)
       btn.addTarget(self, action:  #selector(self.savetest(_:)), for: .touchUpInside)
       btn.setTitleColor(UIColor.colorWithHex(hexColor: 0x8F8F8F), for: .normal)
       btn.backgroundColor = UIColor.white
       btn.layer.borderColor = UIColor.colorWithHex(hexColor: 0xE0E0E0).cgColor
       btn.layer.borderWidth = 1
       return btn
}()

3.Timer实现获取验证码倒计时按钮

private var countdownTimer: Timer?
   
private var remainingSeconds: Int = 0 {
   willSet {
       btn_phoneVerificationCode.setTitle("重新获取\(newValue)秒", for: .normal)
           
       if newValue <= 0 {
           btn_phoneVerificationCode.setTitle("获取验证码", for: .normal)
           isCounting = false
       }
   }
}
   
var isCounting = false {
   willSet {
       if newValue {
           countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
           remainingSeconds = 60
       } else {
           countdownTimer?.invalidate()
           countdownTimer = nil
       }
       btn_phoneVerificationCode.isEnabled = !newValue
   }
}    

@objc private func updateTime() {
   remainingSeconds -= 1
}

/*
点击获取验证码按钮调用
*/
self.isCounting = true
导航栏-###

1.隐藏导航栏

override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
           // 隐藏首页的导航栏 true 有动画
           self.navigationController?.setNavigationBarHidden(true, animated: true)
   }
   
override func viewWillDisappear(_ animated: Bool) {
       super.viewWillDisappear(animated)
       // 跳转页面的导航 不隐藏 false
       self.navigationController?.setNavigationBarHidden(false, animated: true)
   }

2.导航栏属性设置

//防止页面上移,导航栏遮挡
self.navigationBar.isTranslucent = false;
//修改导航栏文字字体和大小
self.navigationController?.navigationBar.titleTextAttributes =
           [NSAttributedString.Key.font: UIFont.italicSystemFont(ofSize: 28)]
//修改导航栏文字颜色
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black]
///导航栏背景颜色
self.navigationController?.navigationBar.barTintColor = UIColor.white
//关闭侧滑返回
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
///导航栏背景图
var image = UIImage()
image = UIImage.init(named: "tabBar_bgImg")!
//这句话按照比例延伸,显示完整图片
image = image.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: UIImage.ResizingMode.stretch)
self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
UIView-###
  • 懒加载
lazy var testView : UIView = {
       let _view = UIView.init(frame: CGRect(x: 20, y: 10, width: 200, height: 200))
       _view.backgroundColor = UIColor.red
       return _view
}() 
  • 设置部分圆角

1.UIView扩展

extension UIView {
   /// SwifterSwift: Set some or all corners radiuses of view.
   ///
   /// - Parameters:
   ///   - corners: array of corners to change (example: [.bottomLeft, .topRight]).
   ///   - radius: radius for selected corners.
   func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
       let maskPath = UIBezierPath(
           roundedRect: bounds,
           byRoundingCorners: corners,
           cornerRadii: CGSize(width: radius, height: radius))

       let shape = CAShapeLayer()
       shape.path = maskPath.cgPath
       layer.mask = shape
   }
}

//调用
//调用前 testView要设置好frame
self.testView.roundCorners([.bottomLeft, .topRight], radius: 100)

2.效果图


下左右上圆角.png

END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容