普通视图

发现新文章,点击刷新页面。
今天 — 2025年11月21日首页

iOS App进入后台时会发生什么

作者 songgeb
2025年11月20日 17:00

根据官方文档(Extending your app’s background execution timeManaging your app’s life cycle)显示

文档查阅时间为2025-11-20

  • 正常情况下,App先进入Background状态,紧接着(时间长短取决于是否通过beginBackgroundTask方法发起任务,但总体都很短)进入Suspended
  • 进入后台时applicationDidEnterBackground会执行,同时进入Background状态,该方法会有5s时间执行其中的任务
  • applicationDidEnterBackground之后,如果没有beginBackgroundTask发起的后台任务,则很快就会进入Suspended状态
  • 进入Suspended状态,App还会在内存中
  • BackgroundSuspended状态的不同点是
    • Background状态下,是可以执行短暂的后台任务
    • Suspended状态下,App代码便不会再执行,收不到任何通知,而且系统可以根据(未其他App腾出内存空间)需要将App终止掉
  • 即使通过beginBackgroundTask开启后台任务也不过最多有30s的执行时间,仅适合执行一些非常重要的任务,比如将一些严重影响用户体验的数据写入磁盘,用作后续状态恢复
  • 如果希望申请更多后台任务执行时间,则需要依赖Background Tasks框架

b0d3522d-c62b-49e2-9f48-01b0a4046b11.png

昨天以前首页

What Auto Layout Doesn’t Allow

作者 songgeb
2025年11月3日 15:38

日常使用Snapkit做约束时经常会遇到约束更新错误或者不允许的操作,本文记录一下Autolayout中哪些操作是不被允许的

前置知识

Size Attributes and Location Attributes

Autolayout中Attributes分为两类:Size Attributes 和 Location Attributes

  • Size Attributes:表示的是尺寸信息,有Width、Height
  • Location Attributes:表示位置信息,有Leading、Left、Trailing、Right、Top、Bottom、Cente(x、y)、Baseline等等

Autolayout的本质

Autolayout的本质是如下形式的等式或不等式:

Item1.Attribute1 [Relationship] Multiplier * Item2.Attribute2 + Constant

Relationship可以是等式,比如:

  • View1.leading = 1.0 * View2.leading + 0
  • View1.width = 1.0 * View2.width + 20

也可以是不等式,比如:

View1.leading >= 1.0 * View2.trailing + 0

需要注意的是式子两边不总是有Attribute,如下所示:

  • View.height = 0.0 * NotAnAttribute + 40.0(✅)
  • View1.height = 0.5 * View2.height(✅)

上述两个约束都是正确的

规则

1. Size Attribute与Location Attribute之间不能做约束

原文:You cannot constrain a size attribute to a location attribute.

错误举例:View1.width = 1.0 * View2.trailing + 0(❌)

2. 不能对Location Attribute设置常量

原文:You cannot assign constant values to location attributes.

错误举例:View1.leading = 0.0 * NotAnAttribute + 20(❌)

3. Location Attribute中不能使用非1的mutiplier

You cannot use a nonidentity multiplier (a value other than 1.0) with location attributes.

错误举例:View1.leading = 0.5 * View2.leading + 20(❌)

4. Location Attribute中不同方向之间不能做约束

For location attributes, you cannot constrain vertical attributes to horizontal attributes.

错误举例:View1.centerX = 1 * View2.centerY + 20(❌)

5. Leading(Trailing)不能与Left(Trailing)做约束

For location attributes, you cannot constrain Leading or Trailing attributes to Left or Right attributes.

错误举例:View1.centerX = 1 * View2.centerY + 20(❌)

修改Constraints需要注意什么

除了上述规则外,在运行时也可能会更新约束,有如下这些支持的修改约束操作:

  • 激活/停用约束(Activating or deactivating a constraint)
  • 修改约束的常量部分(Changing the constraint’s constant value)
  • 修改约束的优先级(Changing the constraint’s priority)
  • 将视图从页面层级中移除(Removing a view from the view hierarchy)
❌
❌