Stanford CS193p iOS开发课程笔记(五)

2015-12-06  本文已影响162人  Dominic1992

2015年12月6日.

在Storyboard中绘制已经定义的UIView

另FaceView中自定义的属性,在Storyboard中可设定

@IBInspectable2.png Attributs inspector2.png

如何限定需加载值的范围

    var happiness: Int = 75  { //Model 0 = vary sad, 100 = ecstatic
        didSet {
            happiness = min(max(happiness, 0),100) //将happiness的值保持在0-100之间
            print("happiness = \(happiness)")
            updateUI() //如果改变了Model则对UI进行更新
        }
    }

其中happiness = min(max(happiness, 0),100)函数利用取大和取小得方法,限定了数值只能保持在0到100之间,即使用户输入2000,happiness也会取100,输入-2000也只会取0

添加手势

    @IBOutlet weak var faceView: FaceView! {
        didSet {
            faceView.dataSource = self   //加载dataSource
            faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:"))  //直接添加代码实现手势方法,也可通过在Storyboard添加手势识别器实现(下方@IBAction func changeHappiness(gesture: UIPanGestureRecognizer)).
            
        }
    }

2.可通过在Storyboard添加手势识别器实现

在UI控件中能找到多种手势识别器,直接将其拖入Storyboard中并创建Action用代码实现即可

Storyboard.png
    private struct Constants {
        static let HappinessGestureScale: CGFloat = 4
    }
    
    @IBAction func changeHappiness(gesture: UIPanGestureRecognizer) {
        switch gesture.state {
        case .Ended: fallthrough
        case .Changed:
            let translation = gesture.translationInView(faceView)
            
            let happinessChange = -Int(translation.y / Constants.HappinessGestureScale)  
            //此处除以HappinessGestureScale = 4 用来控制拖动时笑脸变化的程度,当数字为1时即为拖动了多少y坐标笑脸的y坐标就变化多少
            
            if happinessChange != 0 {
                happiness += happinessChange
                gesture.setTranslation(CGPointZero, inView: faceView)  
                //将translation坐标重置为(0,0)

            }
        default: break
        }
    
    }

上一篇 下一篇

猜你喜欢

热点阅读