ios学习之autolayout自动布局的简单理解 即UIKIt dymanic的使用

本文介绍如何在Swift中使用Autolayout进行自动布局,并通过代码示例展示了如何实现视图间的动态交互效果,包括重力行为、噪声场及碰撞行为等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

autolayout 是苹果为UI设计添加的自动布局的新方法,具体可看这个文档

http://www.cocoachina.com/ios/20151021/13825.html

http://www.cocoachina.com/ios/20151023/13742.html

添加好的部分代码写好了 下不下去了

import UIKit
//定义椭圆类
class Ellipse:UIView{
    override var collisionBoundsType:UIDynamicItemCollisionBoundsType{
    return .Ellipse
    }
}
class ViewController: UIViewController {

    override func viewDidLoad() {
        //创建UIdynaicAnimator的实例
         var animator = UIDynamicAnimator(referenceView: view)
        //添加视图
        let square = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        square.backgroundColor = UIColor.blueColor()
        view.addSubview(square)
        let ellipse = Ellipse(frame:CGRect(x: 0, y: 0, width: 100, height: 100))
        ellipse.backgroundColor = UIColor.yellowColor()
        ellipse.layer.cornerRadius = 50
        self.view.addSubview(ellipse)
        //给view添加的两个行为
        let items = [square,ellipse]
        let gravity = UIGravityBehavior(items: items)
        animator.addBehavior(gravity)
        //添加重力感应模型
        let noiseField = UIFieldBehavior.noiseFieldWithSmoothness(1.0, animationSpeed: 0.5)
        noiseField.addItem(square)
        noiseField.addItem(ellipse)
        noiseField.strength = 0.5
        animator.addBehavior(noiseField)
        //再添加另外一个行为
        let collision = UICollisionBehavior(items: items)
        collision.setTranslatesReferenceBoundsIntoBoundaryWithInsets(UIEdgeInsets(top: 20, left: 5, bottom: 5, right: 5))
        animator.addBehavior(collision)
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值