<?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>AttributedString &#8211; 隨心所欲</title>
	<atom:link href="https://doeverythingiwant.com/tag/attributedstring/feed/" rel="self" type="application/rss+xml" />
	<link>https://doeverythingiwant.com</link>
	<description>iOS Developer 的隨筆記錄</description>
	<lastBuildDate>Sun, 18 May 2025 09:33:19 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://doeverythingiwant.com/wp-content/uploads/2025/08/cropped-0802.png</url>
	<title>AttributedString &#8211; 隨心所欲</title>
	<link>https://doeverythingiwant.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>[SwiftUI] AttributedString and Hyperlink</title>
		<link>https://doeverythingiwant.com/swiftui-attributedstring-and-hyperlink/</link>
					<comments>https://doeverythingiwant.com/swiftui-attributedstring-and-hyperlink/#respond</comments>
		
		<dc:creator><![CDATA[艾普利]]></dc:creator>
		<pubDate>Sun, 18 May 2025 09:33:16 +0000</pubDate>
				<category><![CDATA[寫程式]]></category>
		<category><![CDATA[AttributedString]]></category>
		<category><![CDATA[Hyperlink]]></category>
		<category><![CDATA[iOS]]></category>
		<guid isPermaLink="false">https://doeverythingiwant.com/?p=2466</guid>

					<description><![CDATA[Photo by Vladislav Klapin on U&#8230;]]></description>
										<content:encoded><![CDATA[
<p class="has-text-align-center wp-block-paragraph">Photo by <a href="https://unsplash.com/@lemonvlad?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash" target="_blank" rel="noopener">Vladislav Klapin</a> on <a href="https://unsplash.com/photos/a-person-holding-up-a-sign-that-says-hello-PVr9Gsj93Pc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash" target="_blank" rel="noopener">Unsplash</a></p>



<p class="wp-block-paragraph">記得還在寫 UIKit 的時候，其實很不喜歡寫 <code>AttributedString</code> 就覺得很麻煩，因為通常會有這樣的需求都是因為想要做超連結(Hyperlink)，記得那時候要做到這樣是很麻煩的，除了要使用 <code>AttributedString</code>外，還要做點擊開網頁…通常&#8230;&#8230;都會想盡辨法打消設計師們的念頭。</p>



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



<p class="wp-block-paragraph">最近因為工作上的需要，所以就來去找找SwiftUI 要怎麼做超連結(Hyperlink)的方式，發現比起過去簡單很多，無論是在設定URL 或是 Handle Action 都很簡單，好用很多。</p>



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



<p class="wp-block-paragraph">若是想要在一串文字中間加上不同的字體或顏色，最常想到的就是 <a href="https://developer.apple.com/documentation/foundation/attributedstring" target="_blank" rel="noopener">AttributedString</a> ，不過，若不是想要做超連結的話，SwiftUI 的 <code>Text</code> 就可以做到了，像這樣:</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code> Text(&quot;Hello, world! &quot;)
 +
 Text(&quot;Go google &quot;)
   .foregroundColor(.orange)
 +
 Text(&quot;website&quot;)</code></pre></div>



<p class="wp-block-paragraph">印出來的結果會是這樣。</p>



<figure class="wp-block-image size-full"><img decoding="async" width="548" height="86" src="https://doeverythingiwant.com/wp-content/uploads/2025/05/截圖-2025-05-04-下午4.35.17.png" alt="" class="wp-image-2467" srcset="https://doeverythingiwant.com/wp-content/uploads/2025/05/截圖-2025-05-04-下午4.35.17.png 548w, https://doeverythingiwant.com/wp-content/uploads/2025/05/截圖-2025-05-04-下午4.35.17-300x47.png 300w" sizes="(max-width: 548px) 100vw, 548px" /></figure>



<p class="wp-block-paragraph">不過，如果想要加上 <code>.onTapGesture</code> 的話就沒有辨法了，用 <code>+</code> 串連的<code>Text</code>已經不是單純的 <code>Text</code> ，無法使用<code>.onTapGesture</code> 所以，想要做超連結的話，還是用<code>AttributedString</code>比較好。</p>



<h2 class="wp-block-heading"><code>AttributedString</code></h2>



<p class="wp-block-paragraph"><a href="https://developer.apple.com/documentation/foundation/attributedstring" target="_blank" rel="noopener">AttributedString</a> 是可以讓一串文字裡加入不同樣式的一種方式，這次特別寫出超連結的做法，它的做法是計算出特定字串的 Range ，再依據這個 Range 中的字是需要什麼樣式和顏色，只要能讓它知道需要不一樣的字是什麼，基本上就沒什麼問題。</p>



<p class="wp-block-paragraph"><code>AttributedString</code>中的 <code>AttributeScopes.FoundationAttributes</code> 裡有提供 <code>Link</code> 參數，就是用來做為超連結使用的。</p>



<p class="wp-block-paragraph">以下是實作方式</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>private func getLinkText(_ text: String, linkText: String, linkURL: String) -&gt; AttributedString {
    var attributedString = AttributedString(text)
    attributedString.font = .systemFont(ofSize: 14, weight: .regular)
    attributedString.foregroundColor = Color.gray
        
    if let range = attributedString.range(of: linkText) {
        attributedString[range].font = .systemFont(ofSize: 14, weight: .medium)
        attributedString[range].foregroundColor = Color.orange
        attributedString[range].link = URL(string: linkURL)
    }
        
    return attributedString
}</code></pre></div>



<p class="wp-block-paragraph">解析一下程式碼</p>



<ul class="wp-block-list">
<li><code>var attributedString = AttributedString(text)</code> ，這裡的 <code>text</code> 需要是全部的句子</li>



<li><code>attributedString.range(of: linkText)</code>，<code>linkText</code> 就是想要做成超連結的文字段</li>



<li><code>attributedString[range].link</code>，這裡寫入想要開啟的網站</li>
</ul>



<p class="wp-block-paragraph"><code>font</code> 與 <code>foregroundColor</code> 可以自行設定，應該有人有發現，像 <code>View</code> 的 <code>foregroundColor</code> 已經<mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color">Deprecated</mark> 了，現在都使用 <code>foregroundStyle</code> ，但這裡的 <code>foregroundColor</code> 是 <code>AttributeScopes</code>裡的，不是 <code>View</code> 的喔。</p>



<h2 class="wp-block-heading">Handle link</h2>



<p class="wp-block-paragraph">已經組好有中間有超連結的字串了，再來就直接用 <code>Text</code> 就可以了，最後的範例是要怎麼Handle link 行為</p>



<div class="hcb_wrap"><pre class="prism line-numbers lang-swift" data-lang="Swift"><code>Text(getLinkText(&quot;Hello, world! Go google&quot;, linkText: &quot;google&quot;, linkURL: &quot;https://www.google.com.tw&quot;))
                .environment(\.openURL, OpenURLAction { _ in
                    return .systemAction
                })</code></pre></div>



<p class="wp-block-paragraph">重要的就是使用 <a href="https://developer.apple.com/documentation/swiftui/openurlaction" target="_blank" rel="noreferrer noopener">OpenURLAction</a> ，與 <code>environment(\.openURL)</code> 一起使用，就可以Handle Link Text 點擊的行為，範例上寫的 <code>.systemAction</code> 的行為，就是指外開至Safari ，以下簡單說明 <code>OpenURLAction</code> 的回傳值。</p>



<ul class="wp-block-list">
<li><a href="https://developer.apple.com/documentation/swiftui/openurlaction/result/handled" target="_blank" rel="noreferrer noopener">handled</a> : 就是自行處理，例如，想要直接用 <code>.sheet</code> 開啟網頁，這時候就需要 <code>return handled。</code></li>



<li><a href="https://developer.apple.com/documentation/swiftui/openurlaction/result/discarded" target="_blank" rel="noopener">discarded</a> : 就是不做任何處理。</li>



<li><a href="https://developer.apple.com/documentation/swiftui/openurlaction/result/systemaction" target="_blank" rel="noopener">systemAction</a> : 就是直接外開至Safari ，由Safari 幫你開網頁</li>



<li><a href="https://developer.apple.com/documentation/swiftui/openurlaction/result/systemaction(_:)" target="_blank" rel="noopener">systemAction(_:)</a> : 是用 Safari 開，但是還可以帶別的 URL 或是需要加工URL (這個URL 是指Swift 裡的 <a href="https://developer.apple.com/documentation/Foundation/URL" target="_blank" rel="noopener">URL</a> 物件喔)</li>
</ul>



<h2 class="wp-block-heading">最後</h2>



<p class="wp-block-paragraph">只要記得上述這些東西，就可以比較簡單地寫出超連結的文字了，畢竟是手機，建議二組超連結的文字不要太近，不然很容易會點錯喔…</p>



<p class="wp-block-paragraph">最後，祝大家 Coding 愉快!!</p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://doeverythingiwant.com/swiftui-attributedstring-and-hyperlink/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
