<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Drop and Drag &#8211; 隨心所欲</title>
	<atom:link href="https://doeverythingiwant.com/tag/drop-and-drag/feed/" rel="self" type="application/rss+xml" />
	<link>https://doeverythingiwant.com</link>
	<description>iOS Developer 的隨筆記錄</description>
	<lastBuildDate>Sun, 09 Jun 2024 10:41:04 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://doeverythingiwant.com/wp-content/uploads/2025/08/cropped-0802.png</url>
	<title>Drop and Drag &#8211; 隨心所欲</title>
	<link>https://doeverythingiwant.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SwiftUI &#8211; Drop &#038; Drag List</title>
		<link>https://doeverythingiwant.com/swiftui-drop-drag-list/</link>
					<comments>https://doeverythingiwant.com/swiftui-drop-drag-list/#respond</comments>
		
		<dc:creator><![CDATA[艾普利]]></dc:creator>
		<pubDate>Sun, 09 Jun 2024 10:41:02 +0000</pubDate>
				<category><![CDATA[寫程式]]></category>
		<category><![CDATA[Drop and Drag]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[SwiftUI]]></category>
		<guid isPermaLink="false">https://doeverythingiwant.com/?p=2280</guid>

					<description><![CDATA[忘記是那一年的WWDC公布了一個拖曳相關的功能，主要是讓你可&#8230;]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">忘記是那一年的WWDC公布了一個拖曳相關的功能，主要是讓你可以將iPhone 的資料像是圖片之類的丟到iPad 或Mac 上，因此有了 API 可以用在 Drop &amp; Drag 動作上。</p>



<p class="wp-block-paragraph">最近因為工作需要花了一些時間在研究Drop &amp; Drag 應該要怎麼寫，需要實作的是一般的拖拉元件改變它的順序，並不需要讓它能拖到另一個裝置上，寫作上就會比較簡單一點。</p>



<span id="more-2280"></span>



<p class="wp-block-paragraph">參考以下文件與官方網站來練習</p>



<p class="wp-block-paragraph"><a href="https://dogpa0130.medium.com/swift-practice-177-swiftui-%E6%8B%96%E6%9B%B3-drop-drag-%E6%94%B9%E8%AE%8A%E9%99%A3%E5%88%97array%E4%BD%8D%E7%BD%AE-b63ff5edb935" target="_blank" rel="noreferrer noopener">Swift Practice # 177 SwiftUI 拖曳 Drop &amp; Drag 改變陣列Array位置</a></p>



<p class="wp-block-paragraph"><a href="https://mobileappsacademy.medium.com/drag-and-drop-list-in-swiftui-30b53682d447" target="_blank" rel="noreferrer noopener">Drag and Drop List in SwiftUI</a></p>



<p class="wp-block-paragraph"><a href="https://developer.apple.com/documentation/swiftui/drag-and-drop" target="_blank" rel="noreferrer noopener">Apple Documentation &#8211; Drag and Drop</a></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Start</h2>



<p class="wp-block-paragraph">一開始當然要先做一個要進行拖曳的List，建立一個顯示各種茶的List</p>



<p class="wp-block-paragraph">建立List 的 Item View</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>struct TeaItemView: View {
    
    var title: String
    
    var body: some View {
        HStack {
            Text(title)
                .font(.system(size: 26))
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 30)
        .background(.green)
        .clipShape(RoundedRectangle(cornerRadius: 20))
        
    }
}</code></pre></div>



<p class="wp-block-paragraph">再建立一個用 <code>ForEach</code> 做的 List </p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>import SwiftUI

struct ContentView: View {
    
    @State private var draggedItem: String?
    @State private var fruitItems = [&quot;&#x1fad6; Tea&quot;, &quot; &#x2615; Coffee&quot;, &quot; &#x1f9c3; Juice&quot;, &quot;&#x1f9cb;Pearl milk tea&quot;, &quot;&#x1f95b; Milk&quot;, &quot;&#x1f379; Fruit tea&quot;, &quot;&#x1f9c9; Mate tea&quot;, &quot;&#x1f375; Matcha tea&quot;]
    
    var body: some View {
        
        ScrollView(showsIndicators: false) {
            VStack(spacing: 10) {
                ForEach(fruitItems, id: \.self) { fruit in
                    TeaItemView(title: fruit)
                }
            }
            .padding(.horizontal, 20)
        }
        .background(.black)
    }
}</code></pre></div>



<p class="wp-block-paragraph"><code>draggedItem</code> 是負責記錄要被拖曳的元件，再來Run 一下程式，會出現下面畫面</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="295" height="640" src="https://doeverythingiwant.com/wp-content/uploads/2024/06/teaList.gif" alt="" class="wp-image-2285"/></figure>
</div>


<h2 class="wp-block-heading">DrogDelegate</h2>



<p class="wp-block-paragraph">如果要讓List 的元件可以被拖曳，必須實作 DropDelegate 這個Protocol，新增一個 DropDragDelegate 來實作它</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>import SwiftUI

struct DropDrapDelegate: DropDelegate {
    
    let destinationItem: String
    
    @Binding var fruits: [String]
    @Binding var draggedItem: String?
    
    func dropUpdated(info: DropInfo) -&gt; DropProposal? {
        return DropProposal(operation: .move)
    }
    
    func performDrop(info: DropInfo) -&gt; Bool {
        draggedItem = nil
        return true
    }
    
    func dropEntered(info: DropInfo) {
        if let draggedItem {
            let fromIndex = fruits.firstIndex(of: draggedItem)
            if let fromIndex {
                let toIndex = fruits.firstIndex(of: destinationItem)
                if let toIndex, fromIndex != toIndex {
                    withAnimation {
                        self.fruits.move(fromOffsets: IndexSet(integer: fromIndex), toOffset: (toIndex &gt; fromIndex ? (toIndex + 1) : toIndex))
                    }
                }
            }
        }
    }
}</code></pre></div>



<p class="wp-block-paragraph">在這個 Delegate 中有幾個需要實作的 function</p>



<p class="wp-block-paragraph"><code>func dropUpdated(info: DropInfo) -> DropProposal?</code>  </p>



<p class="wp-block-paragraph">宣告這個拖曳是要什麼動作，以範例來說只是要做移動，所以是 <code>.move</code>，可以去官方文件查看 <code>DropProposal</code> 可以知道更多設定值，預設值會是 <code>nil</code>。</p>



<p class="wp-block-paragraph"><code>func performDrop(info: DropInfo) -> Bool</code></p>



<p class="wp-block-paragraph">拖曳完成的時候會呼叫到它，回傳 <code>true</code> 表示 Drop was successful</p>



<p class="wp-block-paragraph"><code>func dropEntered(info: DropInfo)</code></p>



<p class="wp-block-paragraph">在這個拖曳要做些什麼? 這是我對這個function 的理解，這個範例主要是要交換順序，所以裡面寫的就是交換的方式</p>



<h2 class="wp-block-heading">View</h2>



<p class="wp-block-paragraph">再回到 View ，將 <code>OnDrop</code> 與 <code>OnDrag</code> 加到剛剛寫好的 List 中</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>ScrollView(showsIndicators: false) {
    VStack(spacing: 10) {
        ForEach(fruitItems, id: \.self) { fruit in
            TeaItemView(title: fruit)
                .onDrag({
                    draggedItem = fruit
                    return NSItemProvider()
                })
                .onDrop(of: [.text], delegate: DropDrapDelegate(destinationItem: fruit, fruits: $fruitItems, draggedItem: $draggedItem))
            
        }
    }
    .padding(.horizontal, 20)
}
.background(.black)
</code></pre></div>



<p class="wp-block-paragraph"><code>onDrag</code> </p>



<p class="wp-block-paragraph">這個的重點在於 <code>NSItemProvider</code> ，<code>NSItemProvider</code> 它是為了在進行 <code>Drag-and-drop</code> 或是 <code>Copy-and-paste</code> 時傳送資料或檔案用的，設定方式我自己是不太理解，常見的設定是 <code>URL</code>，這個範例用不到，就直接建立一個空的ItemProvider，若有需要傳送資料到不同裝置上的話應該需要留意一下。</p>



<p class="wp-block-paragraph"><code>onDrop(of:delegate:)</code></p>



<p class="wp-block-paragraph">設定Type與Delegate ，Delegate 就是先前建立的 DropDrapDelegate，直接代需要的參考就好。</p>



<p class="wp-block-paragraph">Type的設定有二種方式，第一種是給它 <code>The uniform type identifiers</code> ，這是需要可以辨識要傳送的資料，查了一下，應該是可以自定這個 Identifier。第二種是設定 <code>UTType</code> ，在範例中的 <code>[.text]</code> 就是 <code>UTType</code> 裡的 <code>Text</code>，在官方文件中可以看到很多種類型，那<code>UTType</code>是什麼? 它其實就是指要進行<code>load, send, or receive</code>的資料類型。</p>



<p class="wp-block-paragraph">加上 <code>onDrag</code> 與 <code>onDrop</code> 之後就可以進行拖曳了</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="295" height="640" src="https://doeverythingiwant.com/wp-content/uploads/2024/06/Finish.gif" alt="" class="wp-image-2288"/></figure>
</div>


<p class="wp-block-paragraph">可以在 <a href="https://github.com/AprilXMoon/DragDropDemo" target="_blank" rel="noreferrer noopener">Github</a> 上下載這個範例程式</p>



<p class="wp-block-paragraph">最後祝大家 Coding 愉快!!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://doeverythingiwant.com/swiftui-drop-drag-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
