美文网首页
scala模仿swift的属性观察器

scala模仿swift的属性观察器

作者: 奈文摩尔定律 | 来源:发表于2016-11-02 15:30 被阅读37次

使用swift开发ios的时候把业务可以写入到属性观察器,我也挺喜欢叫钩子函数


    var currentIndex:Int?{
        didSet{
            if currentIndex != 3{
                titleViewCells![currentIndex!].focusCell()
                titleViewCells!.filter{$0.data?.index != currentIndex}.forEach{$0.blurCell()}
                if let scrollview = scrollerContainer {
                    //滚动,切换子控制器
                    var offset = scrollview.contentOffset
                    offset.x = CGFloat(currentIndex!) * scrollview.width
                    scrollview.setContentOffset(offset, animated: true)
                }
            }else{
               forwardPage()
            }
        }
    }

currentIndex是子控制器容器的索引,他的更新会引起子控制器的切换,其实这个实现完全可以在属性setter函数重写(重载也可以)

class People(name:String,about:String){
    type  observer = (Int) => Unit
    private var privateAge = 0
    def age = {privateAge}
    def age_(willSet:observer=(newage:Int)=>{println(s"willSet ${newage}")},
             newValue: Int,
             didSet:observer=(newage:Int)=>{println(s"didSet ${newage}")}):Unit= {
                willSet(newValue);
                privateAge = newValue
                didSet(newValue);
    }
}
object KVOObject{
    def main(args: Array[String]): Unit = {
        val p = new People("twp","programer")
            p.age_(
                (newage:Int)=>{
                        println(s"newage is ${newage} and willSet")
                        println(s"age oldval is ${p.age}")
                    },
                26,
                (newage:Int)=>{
                    println(s"newage is ${newage} and didSet")
                    println(s"age  is ${p.age}")
                })
        p.age_(newValue = 26) }
}

这来实现组装的回调来编写业务处理还是很方便的。(第一次写简书,多多见谅)

相关文章

  • scala模仿swift的属性观察器

    使用swift开发ios的时候把业务可以写入到属性观察器,我也挺喜欢叫钩子函数 currentIndex是子控制器...

  • swift属性观察器

    OC里面可以重写属性的get和set方法,swift里没有对应的写法,但有属性观察器属性观察器会监控和响应属性值变...

  • swift 属性观察器

    概念 用来监视属性值变化,当属性值发生改变时可以对此作出响应。可以为除了延迟存储属性之外的其他存储属性添加属性观察...

  • swift 属性观察器

    简单例子: 为了保存右边中间那个价格数自己还想了很久怎么写程序,因为那个文本是一个字符串,它夹带有一个币种符号,刚...

  • swift 属性观察器

  • swift 属性专题

    计算属性 简写设置器 在swift中setter/getter方法的实现 属性观察者 属性包装 属性包装映射值

  • Swift属性观察方法willSet和didSet

    Swift-属性观察着(willSet和didSet) 属性观察者,类似于触发器.用来监视属性的除了初始化之外的属...

  • 浅谈swift中的属性观察者

    Swift-属性观察者(willSet和didSet) 属性观察者,类似于触发器.用来监视属性的除了初始化之外的属...

  • Swift 继承属性观察器

    关于 didSet 和 willSet 这两个方法, 在继承的时候, 父类的也会执行, 所以尽量不要像下面那样来实...

  • Swift-计算属性、属性观察器

    计算属性 计算属性不直接存储值,而是提供一个 getter 和一个可选的 setter,来间接获取和设置其他属性或...

网友评论

      本文标题:scala模仿swift的属性观察器

      本文链接:https://www.haomeiwen.com/subject/nqwvuttx.html