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
相關文章
相關標籤/搜索