The magic of view preferences in SwiftUI

栏目: IT技术 · 发布时间: 5年前

内容简介:I took a one week break fromTo learn more about the benefits of the environment feature take a look at

I took a one week break from SwiftUI topic when we were talking about building networking in Swift using functions . It’s time to go back to SwiftUI . This week we will talk about view preferences, which is another powerful concept of SwiftUI views that allows us to pass data through view hierarchy.

Preferences

SwiftUI has the environment concept which we can use to pass data down into a view hierarchy. Parent views share its environment with child views and subscribe to the changes. But sometimes we need to pass data up from child view to the parent view, and this is where preferences shine. Let’s take a look at the small example.

To learn more about the benefits of the environment feature take a look at “The power of Environment in SwiftUI” post .

import SwiftUI

struct ContentView: View {
    let messages: [String]

    var body: some View {
        NavigationView {
            List(messages, id: \.self) { message in
                Text(message)
            }.navigationBarTitle("Messages")
        }
    }
}

Here is an excellent example of preference usage. navigationBarTitle modifier uses the preference feature to pass the data up to the NavigationView , which renders it in the navigation bar. Let’s take a look at the possible internal implementation of the navigationBarTitle modifier.

import SwiftUI

struct NavigationBarTitleKey: PreferenceKey {
    static var defaultValue: String = ""

    static func reduce(value: inout String, nextValue: () -> String) {
        value = nextValue()
    }
}

extension View {
    func navigationBarTitle(_ title: String) -> some View {
        self.preference(key: NavigationBarTitleKey.self, value: title)
    }
}

In order to use preferences, we need to declare a struct conforming PreferenceKey protocol. PreferenceKey has two requirements, default value for preference and reduce method. Reduce method maintains the logic that combines multiple values into a single one. You might need to replace or append values. In our case, we need to replace the old title with the current one. As you can see, we use a preference modifier to set a value.

struct ContentView: View {
    let messages: [String]

    var body: some View {
        NavigationView {
            List(messages, id: \.self) { message in
                Text(message)
            }.navigationBarTitle("Messages")
        }.onPreferenceChange(NavigationBarTitleKey.self) { title in
            // you have to set title value in the navigation bar here
            print(title)
        }
    }
}

In the example above, we use the onPreferenceChange modifier to observe NavigationBarTitleKey . SwiftUI will call this closure whenever view sets a new value for the preference.

Understanding the size of child view

Sometimes we need to get the size of the child view to make some offset, and it is another excellent example of preference usage in SwiftUI . Let’s take a look at how we can use preferences to fetch the size of the child view.

struct SizePreferenceKey: PreferenceKey {
    static var defaultValue: CGSize = .zero

    static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
        value = nextValue()
    }
}

struct SizeModifier: ViewModifier {
    private var sizeView: some View {
        GeometryReader { geometry in
            Color.clear.preference(key: SizePreferenceKey.self, value: geometry.size)
        }
    }

    func body(content: Content) -> some View {
        content.background(sizeView)
    }
}

Here we have a SizeModifier struct, which attaches a geometry reader to a view as a background to read its size. It is a pretty useful technique that allows us to calculate the size of the view. Now we can understand the size of the view using onPreferenceChange modifier.

To learn more about the benefits of the view modifiers take a look at ViewModifiers in SwiftUI .

struct ScrollView<Content: View>: View {
    let content: Content

    @GestureState private var translation: CGSize = .zero
    @State private var contentSize: CGSize = .zero
    @State private var offset: CGSize = .zero

    private var dragGesture: some Gesture {
        DragGesture(minimumDistance: 0)
            .updating($translation) { value, state, _ in
                state = value.translation
        }.onEnded { value in
            self.offset = value.translation
        }
    }

    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }

    var body: some View {
        GeometryReader { geometry in
            self.content
                .fixedSize()
                .offset(self.offset)
                .offset(self.translation)
                .modifier(SizeModifier())
                .onPreferenceChange(SizePreferenceKey.self) { self.contentSize = $0 }
                .gesture(self.isScrollable(geometry.size) ? self.dragGesture : nil)
        }.clipped()
    }

    private func isScrollable(_ size: CGSize) -> Bool {
        contentSize.width > size.width || contentSize.height > size.height
    }
}

Here is the possible implementation of ScrollView that uses preferences to understand the size of its content and enable/disable scrolling based on that value. I use this implementation only for the demo, please don’t use it in production.

Conclusion

Today we talked about another very great feature of SwiftUI . Preferences feature has the same power as the environment, but instead, it uses reversed direction to pass the data. I’m sure you won’t need it very often, but you should know about it. I hope you enjoy the post. Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading, and see you next week!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

未来是湿的

未来是湿的

[美] 克莱·舍基 / 胡泳、沈满琳 / 中国人民大学出版社 / 2009-5 / 39.80

一位妇女丢掉了手机,但征召了一群志愿者将其从盗窃者手中夺回。一个旅客在乘坐飞机时领受恶劣服务,她通过自己的博客发动了一场全民运动。在伦敦地铁爆炸案和印度洋海啸中,公民们用可拍照手机提供了比摄影记者更完备的记录。世界上最大的百科全书是由管理甚少的参与者们撰写的…… 不论在何处,你都能看见人们走到一起彼此分享,共同工作,或是发起某种公共行动。一部集众人之力的百科全书、一个丢失手机的传奇,这些事情......一起来看看 《未来是湿的》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具