比较对象地址

可以用 Objectidentifier 结构来唯一标志一个对象:

ObjectIdentifier(Person(name: "James")).uintValue)

通过比较 UnintValue 即可得知是否是同一对象。

协议扩展

protocol BannerViewProtocol: class {
var bannerView: BannerView? { get set }
var containerStackView: UIStackView { get set }
}
extension BannerViewProtocol where Self: UIViewController{
func showBanner( banner: BannerView, animated: Bool, animationDuration: Double) {
bannerView?.removeFromSuperview()
......
containerStackView.insertArrangedSubview(banner, at: 0)
......
}

注意,通过协议扩展,实现让协议也能够实现具体方法(等同于继承),并调用存 储属性。在 showBanner 方法中调用了协议中定义的 bannerView 属性。
当然你还需要让具体的类继承该协议并实现协议中的两个属性:

public class ViewController: BannerViewProtocol { ......
weak var bannerView: BannerView?
lazy var containerStackView: UIStackView = {
......
}()

协议和关联类型

在 protocol 中不支持泛型参数,它通过 assocaitedtype 来支持泛型,比如:

protocol Screen {
associatedtype ItemType
var items: [ItemType] { get set }
}

相当于(伪代码):

protocol Screen<T> {
var items: [T] { get set }
}

这样,实现类可以通过 ItemType 来指定关联类型的具体类型,比如:

class MainScreen: Screen {
typealias ItemType = String var items = [String]()
}

其中对 typealias ItemType 赋值时只能用具体的类,而不能是 protocol。
此外, typealias ItemType = String 可以省略,因为编译器会自动推断关联类型。

subdata 和 dropFirst

let array : [UInt8] = [0,1,2,3,4,5,6,7,8,9,10,11,12] let data = Data(array)
let datadropped = data.dropFirst(2)
let sub = data.subdata(in: 4..<8 ) // gives 4,5,6,7
let sub2 = datadropped.subdata(in: 4..<8) // also gives 4,5,6,7

datadropped是一个 Slice。
它包含数据的子集,但与原始集合共享相同的索引。
它崩溃是因为 datadropped 的第一个索引是 2,而不是 0。 要获得新的 Data 对象,必须这样写:

let datadropped = Data(data.dropFirst(2))

Dynamic font

textField.adjustsFontForContentSizeCategory = true

然后将控件的 font 全部设置为动态字体:

textField.font = .preferredFont(forTextStyle: .body)

dynamic font, 需要重启 app 才能看到效果

你需要监听 UIContentSizeCategory.didChangeNotification 通知,收到通知后重新设置 UI 组件的动态字体属性。

map 遍历时提供 index

let items = payeeList.enumerated().compactMap { (index, item) in generatePayeeItemViewConfig(payee: item, isSelected:
selectedIndex?.section == 1 && index == selectedIndex?.row) }

关于 radioButton/checkButton 的 accessibility

首先设置 id:

radioButton.accessibilityIdentifier = “radioButton"

将 radioButton 添加到 accessibility elements:

accessibilityElements = [titleLabel, descLabel, amountLabel, radioButton]

当 isSelected 被改变时修改 accessibility label:

func configView(
accessibilityProvider: AccessibilityStringProvidable, selected: Bool = false
){ ......
radioButton.isSelected = selected
radioButton.accessibilityLabel = selected ? accessibilityProvider.commonRadioSelected() : accessibilityProvider.commonRadioUnselected()
}

允许用户在 textview/textfield 的任何位置放置光标

从 iOS 7 开始,你想文本编辑框的任意位置放置光标需要更多的技巧,比如⻓按光
标然后拖动或者 Trackpad 模式(⻓按空格键)。 因为系统默认会对输入内容进行单词识别,在输入框中通过点击来调整光标位置
时,系统会自动将光标放置在单词之前或之后。 要改变这种默认行为相当麻烦,并且效果也不理想。你需要:

1、扩展 UITextView

class WCTextView: UITextView {
public var shouldMoveCursor = false
public var recommendedCursorPosition = UITextPosition()
public func moveCursorToRecommendedPosition() {
let range = textRange(from: recommendedCursorPosition, to:
recommendedCursorPosition) selectedTextRange = range
}
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let deltaY = contentOffset.y
let detltaPoint = CGPoint(x: point.x, y: point.y + deltaY)
recommendedCursorPosition = closestPosition(to: detltaPoint) ?? UITextPosition()
shouldMoveCursor = true
return super.hitTest(point, with: event) }
}

2、使用扩展类

let textView = WCTextView() textView.delegate = self

3、实现委托

public func textView(_ textView: UITextView, shouldChangeTextIn range:
NSRange, replacementText text: String) -> Bool { if !text.isEmpty {
self.textView.shouldMoveCursor = false }
return true
}
public func textViewDidChangeSelection(_ textView: UITextView) {
if textView.selectedRange.length == 0, self.textView.shouldMoveCursor {
self.textView.moveCursorToRecommendedPosition()
self.textView.shouldMoveCursor = false }
}

软键盘添加 Done button

extension UITextField {
func addDoneToolbar(onDone: (target: Any, action: Selector)? = nil) {
var doneButton: UIBarButtonItem!
if let onDone = onDone {
doneButton = UIBarButtonItem(title: localizedString(with: "cosmos_common_done"), style: .done, target: onDone.target, action: onDone.action)
} else {
doneButton = UIBarButtonItem(title: localizedString(with:
"cosmos_common_done"), style: .done, target: self, action: #selector(resignFirstResponder))
}
let toolbar = UIToolbar() toolbar.barStyle = .default toolbar.items = [
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),
doneButton ]
toolbar.sizeToFit()
inputAccessoryView = toolbar }
}

用法:

accountNumberField.addDoneToolbar()

或者:

viewController.accountNumberInputView?.addDoneToolbar(onDone: (target: self, action: #selector(doneTap)))

无法校验单引号和双引号

无论正则表达式怎么写,你都无法在 swift 里成功验证单引号和双引号。是因为
Xcode 里的单引号和双引号和 iOS 里的单引号、双引号不是一个字符。 例如:

"^[a-zA-Z0-9#%&()+ ,\\-./:;=?\\[\\]^_|*\ ‘\” ]*$"

在 iphone 上这两个符号实际上是:‘ 和 “,Unicode 码分别是: \U8216 和 \U8220

在 lldb 中打印这两个符号的 unicode 的方法如下:

(lldb) ex inputText.unicodeScalars
(String.UnicodeScalarView) $R4 = { _guts = {
_object = (_countAndFlagsBits = 1, _object = 0x500060000286c620) }
}
(lldb) po Int($R4[$R4.startIndex].value)
8220

因此上述表达式应写为:

"^[a-zA-Z0-9#%&()+ ,\\-./:;=?\\[\\]^_|*\ ‘’'“”\"]*$"

Swift 常见问题相关推荐

  1. Swift项目引入第三方库的方法

     分类: iOS(55)  目录(?)[+] Swift项目引入第三方库的方法 转自 http://blog.shiqichan.com/How-To-Import-3rd-Lib-Into-Swif ...

  2. 百度App Objective-C/Swift 组件化混编之路(二)- 工程化

    作者丨张渝.郭金 来源丨百度App技术 前文<百度App Objective-C/Swift 组件化混编之路>已经介绍了百度App 引入 Swift 的影响面评估以及落地的实施步骤,本文主 ...

  3. combin14_使用SwiftUI,Combin和Swift Package Manager(SPM)构建复杂的模块化架构

    combin14 We should imagine a modular architecture like a modular building. We need to put pre-design ...

  4. 汇集了很多swift 学习指南

    https://github.com/ipader/SwiftGuide 1,059  Unstar 7,294 Fork1,966 ipader/SwiftGuide  Code  Issues 0 ...

  5. 【环信IM集成指南】iOS端常见问题整理(1)

    1.集成IM如何自定义添加表情组 集成环信IM自定义添加表情组 - IM Geek开发者社区-移动开发者社区-开源社区-IM Geek官网 2.旧版音视频与EaseCallKit兼容升级方案 旧版音视 ...

  6. 用Swift搭建API Server,Vapor + PostgreSQL + Docker + ECS + OSS

    目录 一.Vapor代码简介 1. 项目文件结构 2. 文件/文件夹 简介 3. 部分内容详细展开 1> CommonResponse.swift 2> HTTPCode+Message. ...

  7. Swift SnapKit布局注意事项

    SnapKit布局注意事项 Snapkit 简单布局Demo 常见问题一:updateConstraints 常见问题二:snapkit更改布局动画效果 常见问题三:两个自适应宽度控件,导致右边的自适 ...

  8. swift 高仿爱鲜蜂

    高仿爱鲜蜂 源码github 从swift发布1.0版本时就一直关注着它的成长.目前swift已经比较成熟,可以用来开发完整项目. 现在是时候使用swift练练手了. "爱鲜蜂"是 ...

  9. Swift 语言指南

    Swift 语言指南 @SwiftLanguage 更新于 2016-1-5,更新内容详见 Issue 43.往期更新回顾详见<收录周报> 这份指南汇集了 Swift 语言主流学习资源,并 ...

最新文章

  1. SANS:2014年安全分析与安全智能调研报告
  2. C# WinForm开发系列 - WebBrowser
  3. 基于Html5的移动端开发框架的研究
  4. 保护程序猿滴眼睛-----修改VS 2008 编辑器颜色 (修改 chrome浏览器的背景色)
  5. 如何使用HttpModule来实现我们日常的应用:
  6. php操作kafka
  7. 新年就是要你红!华为Mate 20 Pro馥蕾红璨星蓝来袭
  8. python能做什么-python都能干什么用
  9. [转载]生活在 Emacs 中
  10. idea mysql做登录界面_IDEA下创建SpringBoot+MyBatis+MySql项目实现动态登录与注册功能...
  11. 卫星通信系统按照工作轨道分类
  12. 学完后端还要学前端,在这之间还有中间件
  13. STM32F103的SPI口进行OLED屏的使用
  14. 超赞Win10日历悬停效果,爱了爱了(使用HTML、CSS和vanilla JS)
  15. Fisher线性判别
  16. Java家庭记账程序
  17. Sperax月报 | 2021年8月
  18. stay_foolish_stay_hungry(没事多看看)
  19. Spring Security认证_Remember Me
  20. 超细节的javaWeb知识点总结

热门文章

  1. CString中TrimLeft()与TrimRight()的用法
  2. 计算机验证你的身份,验证您的身份在这台电脑 – Windows 10 | MOS86
  3. php调色板快捷键,Linux_制作简单实用的调色板工具,把如下代码加入body区域 - phpStudy...
  4. 为我的躯壳找一副灵魂--聆听范曾大师讲座有感
  5. 2022年西藏最新食品安全管理员模拟考试试题及答案
  6. 安搭Share:忙里偷闲,也是生活的一种乐趣
  7. 网页通过CSS写出生日倒计时(利用:日期倒计时、元素自动旋转、边框视觉按钮效果)[直接复制代码即可实现、含注释]
  8. windows关闭windows正在检查该问题的解决方案
  9. CSDN博客排名记录
  10. 【POJ No. 1797】重型运输 Heavy Transportation