chapter5,6,7笔记

chapter5 Keyframe Animations

有的时候需要支持多重,有序列的动画合并,这个时候就需要用到Keyframe Animations,使用它可以让代码更加整洁,简单。直接调用:

/* withDuration:动画持续时间
   delay: 延迟多久开始
   option: 和普通动画的option不同,这个option是UIViewKeyFrameAnimationOptions
而不是 UIViewAnimationOptions
   animations:加入想要的动画
   completion:动画完成执行动作
*/
UIView.animateKeyframes(withDuration: 1.5, delay: 0.0,option:[], animations: {
      //add keyframes
      /* withRelativeStartTime: 动画开始时间,取值0到1。用百分比取值,
        如果是0.25,代表该动画在1.5s * 0.25 S之后开始执行。
        relativeDuration:动画时间,取值0到1. 也是Duration的百分比
        animation:加入想要的动画
        
      */
      UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: {
        self.planeImage.center.x += 80.0
        self.planeImage.center.y -= 10.0
      })

      UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.4) {
        self.planeImage.transform = CGAffineTransform(rotationAngle: -.pi / 8)
      }

      UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25) {
        self.planeImage.center.x += 100.0
        self.planeImage.center.y -= 50.0
        self.planeImage.alpha = 0.0
      }

      UIView.addKeyframe(withRelativeStartTime: 0.51, relativeDuration: 0.01) {
        self.planeImage.transform = .identity
        self.planeImage.center = CGPoint(x: 0.0, y: originalCenter.y)
      }
  }

UIViewKeyFrameAnimationOptions展开:

chapter6 introduction to Auto Layout

约束公式:
  控件1.centerX = mutipuplie * 控件2.centerX + constant

chapter7 Animating Constraints

对于布局好之后的控件,使用动画就需要改变控件的约束来重新布局
核心类:NSLayoutConstraint:代表所创建的的所有约束

两种获取需要改变约束的控件的方式:
 
 1.可以通过连线的方式来将需要修改的控件的约束和控件绑定,但是当控件过于多的时候就会很复杂
 2.通过代码,在runtime的时候监视并修改想要改变的约束。UIView有一个constraints(是一个NSLayoutConstraint数组)属性,可以让你获取到所有约束
 
 NSLayoutConstraint来获取特定控件的constraints并改变:

titleLabel.superview?.constraints.forEach { 
constraint in
/*
匹配到titleLable控件,并且属性是中心点的横坐标
改变constant来让titleLable的横坐标左移100
*/
if constraint.firstItem === titleLabel && 
   constraint.firstAttribute == .centerX {
  constraint.constant = isMenuOpen ? -100.0 : 0.0
  return
}
}”

NSLayoutConstraint的匹配规则:


匹配规则

上面这种只改变了constant,当你想修改multiplier或者改变这个约束,你需要移除这个约束并且加一个新的约束(因为multiplier是一个只读属性

添加新的约束,并更新旧约束:

interface Builder中,可以设置约束的identifier,这样可以在run time的时候很简单的获取。(双击约束就能看到)接上一个代码继续写:

/* 检查identifier是否和想要替代的约束的identifier一样,
并通过设置constraint的isActive属性为false来移除旧的约束。
*/
if constraint.identifier == "identifier设置约束的名字" {
    constraint.isActive = false
/* 创建新的约束:
   item:titleLable          firstItem
   attribute:的中心点的Y坐标  attribute
   relateBy:等于                = 
   toItem:父类               superView
   attribute:的中心点的Y坐标   attribute
   multiplier:倍数           * multiplier
   constant:常量             + constant
等同于将下列公式赋值:
firstItem.attribute = multiplier*secondItem.attribute + constant
   新的约束赋值identifier并添加新约束
*/
    let newConstraint = NSLayoutConstraint(
          item: titleLabel,
          attribute: .centerY,
          relatedBy: .equal,
          toItem: titleLabel.superview!,
          attribute: .centerY,
          multiplier: isMenuOpen ? 0.67 : 1.0,
          constant: 5.0)
        newConstraint.identifier = "TitleCenterY"
        newConstraint.isActive = true

  
    return
}

约束更新后调用UIView的layoutIfNeeded方法更新约束。

UIView.animate(withDuration: 1.0, delay: 0.0,
                   usingSpringWithDamping: 0.9, initialSpringVelocity: 8.0, options: .curveEaseIn,
                   animations: {
                    self.view.layoutIfNeeded()
                    let angle: CGFloat = self.isMenuOpen ? .pi / 4 : 0.0
                    self.buttonMenu.transform = CGAffineTransform(rotationAngle: angle)
    }, completion: nil)
新添加控件约束动画

对于新添加一个控件的动画,比如点击一个按钮弹出一个窗口。

先介绍下UIViewtranslatesAutoresizingMaskIntoConstraints属性,这个属性为false就是允许新建视图使用Auto Layout, 而不是AutoresizingMask。iOS 6之前使用的是AutoresizingMask布局。以下是官方文档解释。

If this property’s value is true, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties, allowing you to create a static, frame-based layout within Auto Layout.

Note that the autoresizing mask constraints fully specify the view’s size and position; therefore, you cannot add additional constraints to modify this size or position without introducing conflicts. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false

例子:

/* 设置好后就可以给imageView添加约束了 */
let imageView = UIImageView(image: UIImage(named: "summericons_100px_0\(index).png"))
    imageView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(imageView)
使用NSLayoutAnchor添加约束

NSLayoutAnchor介绍:
https://developer.apple.com/documentation/uikit/nslayoutanchor
简单来说就是苹果对以前复杂的创建约束函数的一个简化版,iOS 9加入的新特性。(leading代表左间距,trailing代表右间距)。NSLayoutGuide就相当于一个方块,可以把零散的控件放进去,然后整体布局。

添加约束并加入动画:

    
    let conX = imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
    let conBottom = imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: imageView.frame.height)
    let conWidth = imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.33, constant: -50.0)
    let conHeight = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor)

    NSLayoutConstraint.activate([conX, conBottom, conWidth, conHeight])

    view.layoutIfNeeded()
    
    UIView.animate(withDuration: 0.8, delay: 0.0,
                   usingSpringWithDamping:  0.6, initialSpringVelocity: 0.0,
                   animations: {
                    conBottom.constant = -imageView.frame.size.height/2
                    conWidth.constant = 0.0
                    self.view.layoutIfNeeded()
    }, completion: nil)

记得添加完约束,调用layoutIfNeeded()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容