当前位置: 首页 > news >正文

swift开发常用代码片段

// 绑定事件
cell.privacySwitch.addTarget(self, action: #selector(RSMeSettingPrivacyViewController.switchTapped(_:)), for: UIControl.Event.valueChanged)

@objc func switchTapped(_ sender: UISwitch) {
  print(sender.isOn)
}

// 跳转页面
var targetVc: UIViewController
targetVc = targetViewController()
navigationController?.pushViewController(targetVc, animated: true)

// 导入指定cell
if cell == nil {
  cell = Bundle.main.loadNibNamed("cell", owner: nil, options: nil)?.first
}

// 隐藏 tableHeaderView
tableView.tableHeaderView?.removeFromSuperview()
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))

// 隐藏 presentView
self.presentingViewController?.dismiss(animated: true, completion: nil)

// 创建 button
lazy private var logoutButton: UIButton = {
  let logoutButton = UIButton()
  logoutButton.setTitle("退出登录", for: .normal)
  logoutButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
  // 文字加粗
  // submitButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
  logoutButton.setTitleColor(UIColor.rs_purple_8127fd, for: .normal)
  logoutButton.addTarget(self, action: #selector(logoutButtonTapped), for: UIControl.Event.touchUpInside)
    
    // 添加阴影
    logoutButton.layer.shadowOpacity = 0.8
    logoutButton.layer.showColor = UIColor.black.cgColor
    logoutButton.layer.shadowOffset = CGSize(width: 0, height: 1)
    logoutButton.clipsToBounds = false // 这行一定要加,而且得加载最后,不然阴影没有效果
  return logoutButton
}()

// 在 viewDidLoad() 中
view.addSubview(logoutButton)
  logoutButton.snp.makeConstraints { make in
      make.height.equalTo(40)
      make.width.equalTo(112)
      make.bottom.equalTo(self.bottomLayoutGuide.snp.top).offset(-20)
      make.centerX.equalToSuperview()
}

// alert 弹框
let alertController = UIAlertController(title: "提示", message: "xxx", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { action in
                    cell.privacySwitch.setOn(true, animated: true) })
let okAction = UIAlertAction(title: "好的", style: .default, handler: { action in
                    cell.privacySwitch.setOn(false, animated: true) })
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// 显示 alert
self.present(alertController, animated: true, completion: nil)

//action sheet
lazy var actionSheet: UIAlertController = {
    let actionSheet = UIAlertController(title: "提示", message: "some info...",
                                        preferredStyle: .actionSheet)
    let muteAction = UIAlertAction(title: "不看", style: .default, handler: nil)
    let unFollowAction = UIAlertAction(title: "取消关注", style: .default, handler: nil)
    let deleteAction = UIAlertAction(title: "举报", style: .destructive, handler: nil)
    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
    actionSheet.addAction(muteAction)
    actionSheet.addAction(unFollowAction)
    actionSheet.addAction(deleteAction)
    actionSheet.addAction(cancelAction)
    return actionSheet
}()

// 显示 action sheet
self.present(self.actionSheet, animated: true, completion: nil)

// 导航栏添加按钮
let submitButton = UIBarButtonItem(title: "提交", style: .plain, target: self, action: #selector(submitButtonTapped))
self.navigationItem.rightBarButtonItem = submitButton

@objc func submitButtonTapped() {
  print("点击了提交...")
}

// 导航栏按钮禁用
self.navigationItem.rightBarButtonItem?.isEnabled = false

// 隐藏导航栏
self.navigationController?.setNavigationBarHidden(true, animated: true)

// textView 限制字数
lazy private var textView: UITextView = {
  let textView = UITextView(frame: CGRect.zero)
  textView.delegate = self
  textView.text = "输入文字..."
  return textView
}()

extension RSSettingFeedbackViewController: UITextViewDelegate {
  func textViewDidChange(_ textView: UITextView) {
    // 限制字数
    if textView.text.count >= 400 {
        textView.text = String(textView.text.prefix(400))
    }
  }
}

// 拍照或从图库选择图片
// 上传照片
// uploadButton action: uploadButtonTapped
func uploadButtonTapped() {
  let picker = UIImagePickerController()
  picker.delegate = self
  picker.allowsEditing = true

  var sourceType = UIImagePickerController.SourceType.camera
  if !UIImagePickerController.isSourceTypeAvailable(sourceType) {
      sourceType = UIImagePickerController.SourceType.photoLibrary
  }
  picker.sourceType = sourceType
  self.present(picker, animated: true, completion: nil)
}

// 获取当前拍摄或选择的照片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let photo = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
        let image = UIImageView.init(frame: self.view.frame)
        image.image = photo
        uploadButton.setImage(photo, for: UIControl.State.normal)
    }
    picker.dismiss(animated: true, completion: nil)
}

// cancel后执行的方法
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
  picker.dismiss(animated: true, completion: nil)
}

// 打开连接(页面跳转)
let str = NSString(format: "itms-apps://itunes.apple.com/app/id%@?action=write-review", VendorConfig.tagAPPID)
UIApplication.shared.openURL(NSURL(string: str as String)! as URL)

// 一个搜索框
lazy var textField: UITextField = {
  let textField = UITextField(frame: CGRect.zero)
  let leftView = UIImageView(image: UIImage(named: "release_search")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal))
  textField.leftView = leftView
  textField.leftViewMode = .always
  leftView.contentMode = .center
  leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 20)
  textField.clearButtonMode = .whileEditing
  textField.placeholder = "搜索..."
  textField.backgroundColor = UIColor.rs_gray_f2f2f2
  textField.font = UIFont.rs_pingfangsc_regular(size: 14)
  textField.cornerRadius = 8
  textField.delegate = self
  return textField
}()

// 添加分隔线
let topLine = UIView()
topLine.backgroundColor = UIColor.rs_gray_d8d8d8

topLine.snp.makeConstraints { (make) in
    make.left.equalTo(15)
    make.right.equalTo(-15)
    make.top.equalTo(addressCell.snp.top).offset(-1)
    make.height.equalTo(1 / kScale)
}

// tableview 去除边框线
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none


// 添加阴影 —— xib 中添加 shadow
targetView.clipsToBounds = false

// 根据屏幕宽度计算图片展示高度
let scale = finalImage.size.height / finalImage.size.width
self.collectionView.snp.makeConstraints { (make) in
    make.left.right.equalToSuperview()
    make.top.equalTo(self.tipLabel.snp.bottom).offset(6)
    make.height.equalTo(self.view.snp.width).multipliedBy(scale)
}

// 给视图添加手势(点击、双击)
// 单击切换音量控制
let singleTap = UITapGestureRecognizer(target: self, action: #selector(changeVolumeStatus))
singleTap.numberOfTapsRequired = 1
// 双击点赞
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
doubleTap.numberOfTapsRequired = 2

// 优先检测双击手势
singleTap.require(toFail: doubleTap)

// 将手势添加到视图
targetView.addGestureRecognizer(singleTap)
targetView.addGestureRecognizer(doubleTap)

// 使用 AVPlayer 播放视频
import AVFoundation
/// 播放器
lazy var avplayLayer: AVPlayerLayer = {
    let avplayLayer = AVPlayerLayer(player: nil)
    avplayLayer.videoGravity = .resizeAspectFill
    return avplayLayer
}()

let url = URL(string: "http://pri-video.v.medlinker.net/5595b16d-72bc-4fcb-bef2-c01327abeab3/10.m3u8")
avplayLayer.player = AVPlayer(url: url!)
let scale = CGFloat(video.wide / video.high)
// 通过视频和容器尺寸计算最终展示尺寸
momentContentHeightConstraint?.update(offset: (kScreenWidth - 20) / scale)
avplayLayer.frame = CGRect(x: 0, y: 0, width: kScreenWidth - 20, height: (kScreenWidth - 20) / scale)
avplayLayer.player?.play()

// tableView 设置背景

// 默认拉伸撑满 tableview
self?.tableView.backgroundView = UIImageView.init(image: UIImage(named: "no_feed"))

// 图片原始尺寸位于 tableview 中央
let bg = UIImageView.init(image: UIImage(named: "no_feed"))
bg.contentMode = .center
self?.tableView.backgroundView = bg

// 子线程执行代码
DispatchQueue.cwl_mainThreadAsync {
    let cell = self.cacheCell as? RSSettingAccountCell
    cell!.formItemValue.text = String(self.fileSizeOfCache()) + "Mb"
    stopLoading()
    let feedbackAlert = UIAlertController(title: nil, message: "清除成功!", preferredStyle: .alert)
    self.present(feedbackAlert, animated: true, completion: nil)
    Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.hideAlert), userInfo: nil, repeats: false)
}

// tableview 隐藏滚动条
tableView.showsVerticalScrollIndicator = false

 

转载于:https://www.cnblogs.com/wx1993/p/10276036.html

相关文章:

  • 五分钟了解身体作息规律
  • jzoj6003. 【THUWC2019模拟2019.1.16】Square (乱搞)
  • MongoDB 之pymongodb
  • Web安全小攻略 | Web高能短文系列
  • 淘淘商城的一些错误
  • SpringBoot2.x升级后的变化
  • 算法学习心得
  • 利用Python讲多张图片合成PDF文件
  • Apache Beam实战指南 | 玩转大数据存储HDFSIO
  • 记一次面试题——call、apply、bind模拟实现的更好方式
  • 逻辑运算符
  • 古郡敦煌迎新年初雪 雪漠风光引游人
  • 台湾大学生在威海研习中华文化 感叹收获太多“惊喜”
  • 如何使用 Druid 和 Kafka 构造 Kappa 架构完成流量分析
  • 利用位运算实现加减乘除
  • (三)从jvm层面了解线程的启动和停止
  • 【跃迁之路】【669天】程序员高效学习方法论探索系列(实验阶段426-2018.12.13)...
  • Angular js 常用指令ng-if、ng-class、ng-option、ng-value、ng-click是如何使用的?
  • Docker入门(二) - Dockerfile
  • eclipse(luna)创建web工程
  • k8s 面向应用开发者的基础命令
  • MQ框架的比较
  • MySQL-事务管理(基础)
  • nodejs调试方法
  • overflow: hidden IE7无效
  • React-redux的原理以及使用
  • 阿里云容器服务区块链解决方案全新升级 支持Hyperledger Fabric v1.1
  • 从零开始的无人驾驶 1
  • 搭建gitbook 和 访问权限认证
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 适配mpvue平台的的微信小程序日历组件mpvue-calendar
  • 国内唯一,阿里云入选全球区块链云服务报告,领先AWS、Google ...
  • ​学习一下,什么是预包装食品?​
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (独孤九剑)--文件系统
  • (过滤器)Filter和(监听器)listener
  • (入门自用)--C++--抽象类--多态原理--虚表--1020
  • (一)基于IDEA的JAVA基础12
  • (转)h264中avc和flv数据的解析
  • (转)iOS字体
  • .gitignore文件设置了忽略但不生效
  • .mysql secret在哪_MySQL如何使用索引
  • .net core 客户端缓存、服务器端响应缓存、服务器内存缓存
  • .NET MVC之AOP
  • .Net Redis的秒杀Dome和异步执行
  • .NET/C# 在代码中测量代码执行耗时的建议(比较系统性能计数器和系统时间)
  • .NET:自动将请求参数绑定到ASPX、ASHX和MVC(菜鸟必看)
  • /etc/fstab和/etc/mtab的区别
  • /etc/sudoers (root权限管理)
  • @Async注解的坑,小心
  • @Transactional 详解
  • [ vulhub漏洞复现篇 ] Hadoop-yarn-RPC 未授权访问漏洞复现
  • [C#]C# OpenVINO部署yolov8图像分类模型
  • [CF407E]k-d-sequence
  • [CSS] 点击事件触发的动画