The magic of view preferences in SwiftUI

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

内容简介: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!


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

查看所有标签

猜你喜欢:

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

深入理解计算机系统(原书第3版)

深入理解计算机系统(原书第3版)

Randal E.Bryant、David O'Hallaron / 龚奕利、贺莲 / 机械工业出版社 / 2016-11 / 139.00元

和第2版相比,本版内容上*大的变化是,从以IA32和x86-64为基础转变为完全以x86-64为基础。主要更新如下: 基于x86-64,大量地重写代码,首次介绍对处理浮点数据的程序的机器级支持。 处理器体系结构修改为支持64位字和操作的设计。 引入更多的功能单元和更复杂的控制逻辑,使基于程序数据流表示的程序性能模型预测更加可靠。 扩充关于用GOT和PLT创建与位置无关代码的......一起来看看 《深入理解计算机系统(原书第3版)》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

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

RGB CMYK 互转工具