fabiochiu/medium-articles huggingface dataset:
You Wouldn’t Believe These Facts Behind Netflix’s ‘Narcos’
By: Audrey Bricker
Tags: Narcos, Facts, Netflix, Colombia, Drugs

When you think of Netflix, you probably think of all the fictional shows about romance. But, recently, Netflix has been releasing more factual shows, based on real life events. One of the major players in this relatively new category is ‘Narcos’.

THIS ARTICLE CONTAINS SPOILERS FOR ‘NARCOS’

This show follows American DEA agents that are tasked with bringing down major Colombian drug cartels. In the first two seasons, the agents are Steve Murphy and Javier Peña. At the end of the second season, Murphy leaves and Peña takes over as the main character and narrator of the series.

1.One thing that Netflix stayed relatively true with is the casting. Many of the actors look very similar to their real life counterparts. Robert Boyd Holbrook, who played DEA agent Steve Murphy, is a prime example of that. Javier Peña came onto the set as a consultant for Pedro Pascal, who plays him.

2. The big facts are the same. The show details three main cartels, the Medellín cartel, the Cali cartel, and the North Valley cartel. These three cartels are all real life cartels that took place in the Colombia’s 1980-ish drug war.

3. Pablo Escobar’s own videotapes were used in set design and costume creation. Escobar liked to document his lavish lifestyle, and so he recorded a lot of his ranch and the people on it.

4. Pablo Escobar was killed on the same exact rooftop in real life and the show. The final rooftop chase scene in season 2 of the show takes place in Medellín, and the ridged roof where Escobar is eventually shot is the exact same place.

‘Narcos’ is by no means a completely factual account of the mid 1980’s Colombian drug trade. In fact, there are some characters in the show that don’t even exist in real life! But, the main characters are generally very factual, and the story is pretty much the same. If you’re looking for true facts of the events, ‘Narcos’ is a good starting place.
What a happy holiday to take a good seshy .
Tags: Health, Money, Travel, Drugs, Psychedelics

What a happy holiday to take a good seshy .

Just plug in and get the best out of it .

Wickr// enterthevoid241

trippyvibes78@gmail.com
Overcoming the Fear of Death During a Psychedelic Experience
By: Sam Woolfe
Tags: Anxiety, Psychology, Mental Health, Death, Drugs

During personal, guided, or group psychedelic sessions, people will often confront a range of issues, from trauma to depression to addiction (sometimes all three together since these problems are often linked). One of the most interesting aspects of the psychedelic experiences, to me personally, is how they can feature confrontations with the key existential concerns that we have as humans: death, meaninglessness, isolation, and freedom.

Continue reading…
Trip with the Aliens it’s a trippy universe.
Tags: Health, Lifestyle, Money, Drugs, Psychedelics

Trip with the Aliens it’s a trippy universe.

We all get what we want and make the best out of it get into the void

Wickr// enterthevoid241

trippyvibes78@gmail.com
December 17th, 2020
By: Daily Journal
Tags: Weed, Journalism, Depression, Drugs, Day In The Life

December 17th, 2020

Still struggling with my depression. I got diagnosed June of 2019 and have been on meds since. They just switched me to a new medication and it’s kind of making me sick and nauseas. I’ve thought a lot about suicide but I know there’s people in my life that would blame themselves no matter what and they don’t deserve to live with that. Even though i’m so fucking tired of being alive, it’s not always bad. I picked up my ex from school today and she’s now a really good friend. I’m a girl btw and I don’t really know my sexuality tbh. I’ve hooked up with girls and have almost been in relationships but I think i just get told to often that it’s wrong and so I have to be straight. My family is also super catholic and strict on it too, i know damn well my dad would kick me out. i know some of you guys out there relate to this and that’s why i chose to write so you guys can follow. so, i went and picked up my ex and we went and got food then went to go do some homework because i’m failing. she helped me do some of it and then i got bored and started crying lmao. i dropped her off at work and then drove to pick up my boyfriend. we met up with some of his friends and then went to nampa to get an ounce and then obviously we went back to the house and sold some and smoked. After that i went home but tomorrow is my friends birthday. we’re al going over in the morning and then the 2 of us are skipping school because i work that night. i think i’m going to do molly but a lot of people think i’m addicted and don’t want me doing it. but i’m a minor and yolo, right?
Pop it and feel the euphoria, bulky deals ready
Tags: Health, Money, Drug, Travel, Psychedelics

your one stop shop for all your stuffs you need, Wickr// enterthevoid241, trippyvibes78@gmail.com
“Ode to Drugs”
By: Kourtney Peel
Tags: Drugs

“Ode to Drugs”

It all starts with a simple taste,

Then you grab people in like a kids cartoon

You can be whatever you choose

A powder, a pill, a liquid

Any shape

Any form

The damage you do is equally as harmful

You cause monsters

You cause families to be split

Many fear you

I watched her go from the person I adored

To the person I hated in less than a year

Because of you.

It all started with a pill

Slowly overtime I grew use to this monster you created

She was no longer the happy, funny woman I knew

That woman was a distant memory.

Many tears shed

Many days were spent questioning why?

But then I circled back to the beginning

It only takes a pill, a liquid. or. a powder

It only takes one taste and then you are too far deep.

You are tempting

Many fail to know you are a vile substance

Ruining lives but;

It only takes one pill.

.
War On Us
By: Yoli Knight
Tags: Life, Love, Poetry, Family, Drugs

War On Us

Photo by Magdalena Smolnicka on Unsplash

Little girl

all done up in style

Walking all those miles

didn’t feel so long

while holding your hand

We’d sing songs

be inspired

by your desire

to provide

the good life

And it was good

But then you let go

Dropped me off

didn’t show up for days

Your ways changed

Became conflicted by life

Choosing between addiction and us

and it wasn’t a choice anymore

Even though you adored us

the drugs fought harder

more muscle than my 10 year old self

could muster

I watched as my hero

hit ground zero

How could we know it would

go like this?

Sitting behind bars

in courtrooms

smiling like we could hide

the dark clouds looming over us

Acting tough

but our hearts were broken

by love on drugs

I’m grown now

live as token

to what I’ve seen

How using can change

what you meant to have happen

in the span of a child’s eyes

Prize the life and the people

Give a second chance

and a fighting chance

to those with needle marks

on their arms
Cocaine ketamine
By: Dosantos Fenades
Tags: Drugs

Cocaine is a powerfully addictive stimulant drug made from the leaves of the coca plant native to South America. Although health care providers can use it for valid medical purposes, such as local anesthesia for some surgeries, recreational cocaine use is illegal. As a street drug, cocaine looks like a fine, white, crystal powder. Street dealers often mix it with things like cornstarch, talcum powder, or flour to increase profits. But we only supply the real quality 100% pure Cocaine and others products.> rcsinfo30@gmail.com

Alprazolam Fentanyl

Blow

Coke

Crack

Rock

Snow

mephedrone

Alpha apvp

mdma

herion

availab

Eric Wang Ju

Chair Man

Man Sales OfficeSkype(infor1465

Branch Web: http://www.rdc-cm.com/

Contact our email (rcsinfo30@gmail.com OR inforsale3@gmail.com)
Cocaine ketamine
Tags: Drugs

Cocaine is a powerfully addictive stimulant drug made from the leaves of the coca plant native to South America. Although health care providers can use it for valid medical purposes, such as local anesthesia for some surgeries, recreational cocaine use is illegal. As a street drug, cocaine looks like a fine, white, crystal powder. Street dealers often mix it with things like cornstarch, talcum powder, or flour to increase profits. But we only supply the real quality 100% pure Cocaine and others products.> rcsinfo30@gmail.com

Alprazolam Fentanyl

B low

Coke

Crack

Rock

Snow

mephedrone

Alpha apvp

mdma

herion

availab

Eric Wang Ju

Chair Man

Man Sales OfficeSkype(infor1465

Branch Web: http://www.rdc-cm.com/

Contact our email (rcsinfo30@gmail.com OR inforsale3@gmail.com)
Cocaine ketamine
Tags: Drugs

Cocaine is a powerfully addictive stimulant drug made from the leaves of the coca plant native to South America. Although health care providers can use it for valid medical purposes, such as local anesthesia for some surgeries, recreational cocaine use is illegal. As a street drug, cocaine looks like a fine, white, crystal powder. Street dealers often mix it with things like cornstarch, talcum powder, or flour to increase profits. But we only supply the real quality 100% pure Cocaine and others products.> rcsinfo30@gmail.com

Alprazolam Fentanyl

Blow

Coke

Crack

Rock

Snow

mephedrone

Alpha apvp

mdma

herion

availab

Eric Wang Ju

Chair Man

Man Sales OfficeSkype(infor1465

Branch Web: http://www.rdc-cm.com/

Contact our email (rcsinfo30@gmail.com OR inforsale3@gmail.com)
Biosimulation Market Size Worth $3.77 Billion By 2024
By: Gaurav Shah
Tags: Services, Drugs, Discovery

The global biosimulation market size is expected to reach USD 3.77 billion by 2024, according to a new report by Grand View Research, Inc., registering a CAGR of 15.4% during the forecast period. Soaring need for advanced generation therapeutics owing to the growing prevalence of chronic diseases, such as cancer and diabetes, is stoking the growth of the biosimulation market.

Moreover, the rising geriatric population worldwide is playing an imperative role in the growth of the market. Aged people are highly susceptible to chronic diseases, which is augmenting the need for highly efficacious drugs. In addition, a growing number of drug resistance cases, high drug relapse rates, and limited availability drugs to treat diseases such as AIDS are leading to high clinical urgency for the adoption of biosimulation in applications such as drug development and drug discovery.

Surging demand for biosimulation software and services can also be attributed to their higher cost-efficiency. This cost efficiency is a result of ability to predict toxicity, adverse reactions, and efficacy of investigational drugs during early stages of product development, thus limiting the probability of drug relapse & adverse events at later stages.

Click the link below:

https://www.grandviewresearch.com/industry-analysis/biosimulation-industry

Further key findings from the report suggest:
Drug Addiction
By: Arham Shahid
Tags: Addiction, Heroin, Effect, Alcohol, Drugs

Drug Addiction

Every one of you, at some time in your life, has been to the doctor with an illness, and the physician gives you a drug to overcome that illness.

So, A drug has two impacts on our lives — positive and negative. Drugs are used to cure a disease or to give a boost to disease. Hence, first of all, we must understand the meaning of drug and their types and their drastic and horrible effects on our body.

WHAT IS A DRUG?

A drug is an externally administered substance that modifies or affects chemical reactions in the body.

TYPES OF DRUGS

Drugs are of two kinds:

Drugs of Use;

Drugs of Abuse;

Drugs of Use are the drugs that are taken to cure an illness. Drugs that are mostly used in our daily lives to treat sudden pangs in our bodies.

For Example:

If a person had a heart attack, he should use Aspirin as it contains salicylic acid which causes blood to thin which in turn reduces heart attacks.

If a person felt a slight pain in the head, he should consume a tablet of Paracetamol.

Drugs of Abuse are the drugs that are consumed to change the mental state or just for enjoyment. These drugs lead to severe addiction. These drugs are also known as Narcotics.

NARCOTICS

Narcotics act like depressants but particularly target the brain. They work as painkillers and may bring the feeling of drowsy well being.

The famous narcotics include:

Heroin;

Alcohol;

Heroin

It is a powerful depressant and drug of abuse.

Dulls the senses,

Reduces hunger,

Drowsiness,

Anxiety,

Stomach upsets,

Sweating,

Goosebumps,

Watering of eyes,

Vomiting,

Diarrhoea,

Hallucinations,

Convulsions,

In severe cases, death may occur.

Alcohol

Alcohol is the most widely used drug in the world and is legally available in many countries. It affects the body very harshly.

Anemia and blockage of a coronary artery,

Hypothermia,

In a pregnant woman, alcohol crossed the placenta and enter the unborn child slows down the growth of the child,

Damages liver cells which harden the detoxification of alcohol called Cirrhosis,

Slows down reaction time,

Cancer of tongue and oesophagus,

Loss of self control,

So if heroin and alcohol consumption is a substantial amount, the consumers will be addicted to them.

According to the survey, from 7.8 billion population of the world, 35 million are drug-addicted which is very startling.

So, drug addiction is very lethal as it provokes detrimental impacts and deterioration of society.
“Junkie Wizdom" an original poem by JMR
By: James Ringe
Tags: Junkie, Drugs, Addiction Recovery, Withdrawal, Drug Rehab

Layin there

On the floor

Needing;

Just-

a little bit more.

Veins

Pulse

In To My

Core.

What?

It's not there?

Life's unfair!

Can't stop;

Can't go on.

In despair!

Seriously-

I Don't Wanna Die!

But it's been like this for so long

I Don't Wanna Lie

Cause lying is ummmm. Just wrong?

I'll give truth a try-

Okay?

I like

Junk that way

Hell -

I like junk all day

What?

And Seriously

I Don't Wanna Die

I just keep on shooting

Searching high...

(Lie)

Okay i'm just looking for a higher high

Cause I can't stop

No!!

Im not1

Shooting fish in a barrel;

I put Horse before the Cart

And...

My Gallery ain't full of no fucking art

Get it?

So-

Do I stop and pray?

That ain't my dogma

Wait for a change

Well if it ever happens

Then on that fine day

Maybe I'll put all this junk away.

And Quit?

They say quittings "so hard"

It takes all your heart -

But Junkie Wisdom knows the truth is-

"The only way to stop is not to start."
U.S. House of Reps Approves Cannabis Research Bill
By: Louis O Neill
Tags: Policy, Weed, Cannabis, Law, Drugs

The U.S. House of Representatives has just passed a bill that would make studying cannabis much more accessible to researchers.

The House of Representatives has passed another cannabis-related bill, following their passage of the MORE (Marijuana Opportunity Reinvestment & Expungement) Act, this time passing a cannabis research bill.

The proposed bill, called the Medical Marijuana Research Act, would allow researchers to use dispensary cannabis for their studies, as opposed to current regulation which only allowed for marijuana grown at the University of Mississippi to be studied.

The bill was introduced by representatives on both sides of the political spectrum, Rep. Earl Blumenauer (D-OR) and Rep. Andy Harris (R-MD). On their justification for the bill, Blumenauer said:

“The cannabis laws in this country are broken, especially those that deal with research. It’s a narrow bill that fixes one of many broken cannabis laws. And I want to hasten to add that this in no way negates the need to move forward with other areas of legalization… But this is sort of a foundational question. No matter where you are, there’s no reason the federal government should impede this critical research.”

Harris, who has typically opposed cannabis legalization, stated that he “agree[s] 100 percent that we need to do this research.”

“Now, unfortunately, because of the public policy we’ve had in place with marijuana and its scheduling, it simply couldn’t be done. You can’t do it under the current scheduling… This is on us. It shouldn’t have taken so long to get to this point.”

The Drug Enforcement Administration (DEA) has come under scrutiny for the past several years for stonewalling research into medical cannabis, given that the DEA hasn’t carried out the evaluation process for 37 applications to cultivate cannabis for medical research purposes after nearly four years of delays.

This has even led to lawsuits levelled against the DEA in the hopes of prompting action from the Drug Enforcement Administration.

The DEA’s inaction has led to the bottlenecking of cannabis research in the U.S., which has drastically halted the capacity for cannabis’s categorization as a Schedule I substance to be changed.

Schedule I status was designed to include all of the “hardest” drugs that had no medicinal benefit while having a high potential for abuse. Other drugs alongside cannabis in the Schedule I status are LSD, MDMA, heroin, magic mushrooms and several others.

Until the gates to researching cannabis are pried open, cannabis restrictions will remain on a federal level in the U.S.

The proposed research bill would remove any limitations on how many entities can register to cultivate research-oriented cannabis, as well as simplifying the registration processes for those who seek to do so.
How to make UserDefaults property wrapper
By: Khoa Pham
Tags: Userdefaults, Swiftui, Swift, Property Wrapper

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
How to make simple HUD in SwiftUI
By: Khoa Pham
Tags: Swift, Swiftui, Overlay, Hud, Progress

Use @ViewBuilder to build dynamic content for our HUD. For blur effect, here I use NSVisualEffectView , but we can use .blur modifier also

struct HUD<Content>: View where Content: View {

let content: () -> Content init(@ViewBuilder content: @escaping () -> Content) {

self.content = content

} var body: some View {

content()

.frame(width: 80, height: 80)

.background(

VisualEffectView(material: .hudWindow)

.clipShape(RoundedRectangle(cornerRadius: 12))

.shadow(color: Color.black.opacity(0.22), radius: 12, x: 0, y: 5)

)

}

}

Then we can make some wrappers for information and progress HUD
SwiftUI and Shake Gesture
By: Nicola De Filippo
Tags: Swiftui, Gesture Recognition, Swift

There isn’t a way to catch the shake gesture only using SwiftUI, so it’s necessary use these frameworks: Uikit and Combine .

Combine is very helpful in this case because how is wrote in the Apple documentation: “Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.”

In the example, the goal is catch the Shake gesture with the UiKit, with the Combine framework we publish this event and get the combine published info in the SwiftUI view that is a subscriber. Let’s start.

We must create a Swift file, ShakeGestureManager.swift

import Foundation

import SwiftUI

import Combine let messagePublisher = PassthroughSubject<Void, Never>() class ShakeViewController: UIViewController { override func motionBegan(_ motion: UIEvent.EventSubtype,

with event: UIEvent?) {

guard motion == .motionShake else { return }

messagePublisher.send()

}

} struct ShakeViewRepresentable: UIViewControllerRepresentable {



func makeUIViewController(context: Context) ->

ShakeViewController {

ShakeViewController()

} func updateUIViewController(_ uiViewController: ShakeViewController,

context: Context) {



}

}

Where the PassthroughSubject is a “A subject that broadcasts elements to downstream subscribers.” (from the Apple documentation). We need it to communicate with the SwiftUI View.

The ShakeViewController is a simple UIViewController that catches the shake Gesture. Like in the case of the Map, it’s not possible to use the UIViewController in the SwiftUI so we must create a struct that implement the UIViewControllerRepresentable that we can use in the SwiftUI View.

Now see the SwiftUI view:

import SwiftUI





var body: some View {

NavigationView {

VStack{

ZStack {

ShakeViewRepresentable()

.allowsHitTesting(false)

VStack {

Text("Shake device to change view!")

}



}.onReceive(messagePublisher) { _ in

self.shaked = true

}

NavigationLink(destination: SecondView(), isActive: $shaked) {

EmptyView()

}

}

}

}

} struct ContentView: View { @State var shaked = falsevar body: some View {NavigationView {VStack{ZStack {ShakeViewRepresentable().allowsHitTesting(false)VStack {Text("Shake device to change view!")}.onReceive(messagePublisher) { _ inself.shaked = trueNavigationLink(destination: SecondView(), isActive: $shaked) {EmptyView()

The state variable shaked it used to store the shaked event. In the navigationview there is a ZStack, where at the bottom (first element) there is the ShakeViewRepresentable that can’t get touch event from the user because allowsHitTesting is false, on the top there is a simple Text message. When the ZStack receives the messagePublisher, the shaked variable become true and the NavigationLink become active so the view navigates to the SecondView (that you can create how you want). Note the use of the EmptyView from the NavigationLink, it used to show nothing but to have a working link. That’s all. I hope that it can be helpful. You can get the code here.
Should I Learn SwiftUI instead of UIKit?
By: Mohammad Azam
Tags: Swift, Swiftui, Swift Programming, Ios Development, iOS

Give a shoutout to Drew Beamer on social or copy the text below to attribute.

As an instructor and an iOS developer, one of the most frequent questions I get asked is “Should I learn UIKit, since SwiftUI is the future”. Before I answer this question let me take you back to 2016, when I was teaching iOS development at The IronYard.

At The IronYard Houston, I was an iOS instructor. Even though in 2016, Swift language was 2 years old, I always started the course with few weeks of Objective-C. The main reason for teaching Objective-C was to teach my students to work with legacy codebase. Technology adoption takes time, the larger the company, the more time it takes. This means if you land a job at a big company then your chances of working with Objective-C are very high. Yes, eventually Objective-C will phase out and Swift will be your default choice but 2016 was definitely not that time.

Now, fast forward to 2020 we face the same situation. Should we ignore the past and look into the future or should we learn from the past to better understand the future? I believe that if you are in the process of learning iOS development, you should start with UIKit. SwiftUI is an amazing framework but it is still at an infancy stage and not many companies are using it. Apart from being new it does have sharp edges, which will become smoother each year with new release.

So, if you are a new to iOS development then start with UIKit. Learn the concepts, make sure your base is strong. Once, you have covered the basics jumping onto SwiftUI will be much easier.

I hope this post has helped you understand why UIKit is still important and how it can help you better plan for SwiftUI.
SwiftUI: Form
By: Sinan Ulusan
Tags: Forms, Swiftui, Turkishkit, Türkçe, Kodlama

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
How to fix Picker not showing selection in SwiftUI
By: Khoa Pham
Tags: Foreach, Id, Picker, Bug, Swiftui

I have an enum that conforms to CaseIterable that I want to show in Picker

enum Position: String, Codable, CaseIterable, Identifiable {

var id: String { rawValue }

case left

case right

case bottom

case top

} Picker(selection: $preference.position, label: Text("Position")) {

ForEach(Preference.Position.allCases) { position in

Text(position.rawValue)

}

}

It compiles and runs just fine, but Picker does not show current selection regardless of any Picker style I choose. It does not update Binding at all.

The fix is to specify id , it looks redundant because of enum conforms to Identifiable , but it fixes the problem

Picker(selection: $preference.position, label: Text("Position")) {

ForEach(Preference.Position.allCases, id: \.self) { position in

Text(position.rawValue)

}

}

Mismatch between rawValue and enum case itself

Reading ForEach once again

init(_ data: Data, content: @escaping (Data.Element) -> Content)

Available when Data conforms to RandomAccessCollection, ID is Data.Element.ID, Content conforms to View, and Data.Element conforms to Identifiable.

So in our case, we use rawValue as id for Identifiable , so there's mismatch between our selection being enum case and items in ForEach , which uses rawValue to uniquely identifies items. So our fix is to explicitly state that we want to use the enum case itself \.self as id for ForEach

What we can also do is to declare enum case itself as id

enum Position: String, Codable, CaseIterable, Identifiable {

var id: Position { self }

case left

case right

case bottom

case top

}
How to make sharing menu in SwiftUI for macOS
By: Khoa Pham
Tags: Sharing, Swiftui, Messages, Mac, Mail

Use NSSharingService.sharingServices(forItems:) with an array of one empty string gives a list of sharing items. There we show image and title of each menu item

import SwiftUI

import AppKit

import EasySwiftUI extension NSSharingService {

static func submenu(text: String) -> some View {

return Menu(

content: {

ForEach(NSSharingService.sharingServices(forItems: [""]), id: \.title) { item in

Button(action: { item.perform(withItems: [string]) }) {

Image(nsImage: item.image)

Text(item.title)

}

}

},

label: {

Text("Share")

Image(systemName: SFSymbol.squareAndArrowUp.rawValue)

}

)

}

}
How to show image and text in menu item in SwiftUI for macOS
By: Khoa Pham
Tags: Swiftui, Color, Menu, Mac, Button

From SwiftUI 2 for macOS 11.0, we have access to Menu for creating menu and submenu. Usually we use Button for interactive menu items and Text for disabled menu items.

The easy way to customize menu with image is to call Menu with content and label . Pay attention to how we use Button and Label inside Content to create interactive menu items

Menu(

content: {

ForEach(collections) { collection in

Button(action: {) {

Label(collection.name, systemImage: SFSymbol.star.rawValue)

}

}

},

label: {

Image(systemName: SFSymbol.bookmarkFill.rawValue)

Text("Add to collection")

}

)

We can also use Image and Text separately. By default SwiftUI wraps these inside HStack automatically for us. For now, color has no effect in Menu , but it works on Text

Image(systemName: SFSymbol.bookmarkFill.rawValue)

.foregroundColor(Color.red)

Text(collection.name)

.foregroundColor(Color.green)

One way to mitigate this is to use Text with icon font. Here I use my FontAwesomeSwiftUI

There’s a problem that only the first Text is shown

Text(collection.icon)

.font(.awesome(style: .solid, size: 18))

.foregroundColor(Color.red)

Text(collection.name)

The solution is to concatenate Text . In SwiftUI, Text has + operator that allows us to make cool attributed strings
Get to Know SwiftUI’s GroupBox
By: Can Balkaya
Tags: Swift, Mobile, Swiftui, iOS, Programming

Styling

SwiftUI provides us with the GroupBoxStyle protocol that allows us to completely change the look and feel of any GroupBox instance. Thanks to this protocol, we can create different styles for any use cases we need. For example, I don’t need a background, corner radius, and I want to change the alignment of elements outside of the Label . To do this, I can code a style like the one below:

struct ListGroupBoxStyle: GroupBoxStyle {

func makeBody(configuration: Configuration) -> some View {

VStack(alignment: .leading) {

configuration.label

configuration.content

}

}

}

All you need to do to create your own GroupBox style is create a struct that conforms to the GroupBoxStyle protocol. You have to create a makeBody function that accepts an instance of Configuration type and returns a new view.

The configuration element allows you to manage GroupBox elements in any way you want by dividing the GroupBox element into two: label and content . You understand what these two elements represent. The reason I use a VStack here is to ensure that all elements are leading aligned.

We can use this style in our GroupBox element as shown below:

struct ContentView: View {

var body: some View {

GroupBox(

label:

Label("AirPods Max", systemImage: "applelogo")

.foregroundColor(.black)

) {

Text("Introducing AirPods Max — a perfect balance of exhilarating high-fidelity audio and the effortless magic of AirPods. The ultimate personal listening experience is here.")

.foregroundColor(.secondary)

}

.groupBoxStyle(ListGroupBoxStyle())

.padding()

}

}

As you can see, we use the groupBoxStyle modifier for using ListGroupBoxStyle . SwiftUI will share it using the environment across all children of the view hierarchy. You can see below how much our element can change:

Finally, let’s create a GroupBoxStyle struct to solve the alignment problem of the GroupBox element. For this, it is enough to change the ListGroupBoxStyle struct a bit:

struct CardGroupBoxStyle: GroupBoxStyle {

func makeBody(configuration: Configuration) -> some View {

VStack(alignment: .leading) {

configuration.label

configuration.content

}

.padding()

.background(Color(.systemGroupedBackground))

.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))

}

}

I just used the background and clipShape methods as an extra. The background method allows us to change the background color of the element. The clipShape method allows us to change the shape of the element.
How to make stepper with plus and minus buttons in SwiftUI for macOS
By: Khoa Pham
Tags: Swiftui, Background, Stepper, List, Button

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
SwiftUI 教程 1.5 指示器
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

ProgressView

ProgressView 有两种呈现形式，一种是菊花样式，另一种是进度条样式，二者分别对应 ProgressViewStyle 中的 CircularProgressViewStyle 和 LinearProgressViewStyle。

如果我们没有通过绑定的浮点类型的值动态更新 ProgressView 的 value 值，那么它的默认样式就是 CircularProgressViewStyle，即菊花样式。比如：

ProgressView()

或者：

ProgressView("加载中...")

我们还可以通过 .foregroundColor(.blue) 改变文字的颜色，如果我们要修改菊花的颜色，那么可以这样指定： .progressViewStyle(CircularProgressViewStyle(tint: .orange)) 。

而要修改进度条的颜色，则可以通过 .accentColor(.orange) 实现。

进度条样式的实现也比较简单，当然我们也可以自定义 ProgressViewStyle。

如下是示例所示的全部代码，供参考：

struct IndicatorsView: View {

@State private var progress = 0.0 {

didSet {

if progress == 100 {

title = "下载完成！"

systemImgName = "checkmark.seal.fill"

} else {

title = "下载ing..."

systemImgName = "square.and.arrow.down"

}

}

}

@State private var title = "下载ing..."

@State private var systemImgName = "square.and.arrow.down"

/// 定时器

private let timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()



var body: some View {

List {

// SectionHeaderView 是笔者自定义的视图控件

Section(header: SectionHeaderView(chapter: "ProgressView", section: nil)) {

ProgressView()

.centerHorizontal() // .centerHorizontal() 是笔者自定义的修饰器



ProgressView("加载中...")

.progressViewStyle(CircularProgressViewStyle(tint: .orange))

.centerHorizontal()

.footnote(".progressViewStyle(CircularProgressViewStyle(tint: .orange))")



ProgressView(title, value: progress, total: 100)

.foregroundColor(.blue)

.accentColor(.orange)

.footnote(".foregroundColor(.blue)

.accentColor(.orange)")



ProgressView(value: progress, total: 100) {

HStack {

Image(systemName: systemImgName)

Text(title)

}

.foregroundColor(.blue)

} currentValueLabel: {

Text("\(Int(progress))%").foregroundColor(.orange)

}

.footnote("自定义视图")

}

.onReceive(timer) { _ in // 接收定时器更新事件

if progress < 100 {

progress = min(100, progress + Double(arc4random_uniform(5)+1))

}

}

}

.listStyle(InsetGroupedListStyle())

}

}
SwiftUI 教程 1.2 字体
Tags: Swift, Tutorial, Swiftui, Apps, iOS

SwiftUI 中的字体，具有动态缩放的特性：

字体的调用：

这里顺便提一下这个属性修饰器，它的定义和初始化方法如下：

@propertyWrapper struct ScaledMetric<Value> where Value : BinaryFloatingPoint

init(wrappedValue: Value)

// Creates the scaled metric with an unscaled value using the default scaling.

init(wrappedValue: Value, relativeTo: Font.TextStyle)

// Creates the scaled metric with an unscaled value and a text style to scale relative to.
SwiftUI 教程 1.7 Swift Package Manager 的使用
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

概览

Swift Package Manager（SPM）是 Xcode 内置的包管理工具，支持远程公/私有库和本地库。

创建 Package Manager

创建方法

两种方法：

在 Xcode 菜单栏依次选中 File > New > Package Manager

在目标文件夹中使用命令： Swift package init

创建完成后，在 Sources 文件下添加代码，然后按 cmd + B 编译。如果发现编译器报错，是因为测试代码有误。如果我们不需要编写测试代码，注释即可。

目录结构

如下是一个 Package 的目录结构：

.

├── Package.swift // 配置文件

├── README.md // 包的功能、使用说明

├── Sources // 源码目录

│ └── Biu

│ └── Print.swift

└── Tests // 测试文件目录

├── BiuTests

│ ├── BiuTests.swift

│ └── XCTestManifests.swift

└── LinuxMain.swift

Package.swift 包含如下内容：

// swift-tools-version:5.3

// The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package(

// 包名

name: "Biu",

// 包对外提供的 products（库、可执行文件）

products: [

.library(

name: "Biu",

targets: ["Biu"]),

],

// 依赖的其它包

dependencies: [

// .package(url: /* package url */, from: "1.0.0"),

],

// 包含的 targets

targets: [

// 每个 target 所需依赖

.target(

name: "Biu",

dependencies: []),

.testTarget(

name: "BiuTests",

dependencies: ["Biu"]),

]

)

本地添加和测试 Package

新建一个 Biu_test 工程，直接将 Biu 目录拖入工程

General -> Frameworks, Libraries, and Embedded Content 下添加 Package

下添加 Package 导入 Package（ import Biu ）即可

注：如遇到无法导入或找不到 Package 的问题，可尝试退出工程或重启 Xcode 解决 🤷‍♂️

发布与更新 Package

可以使用 Git 命令，也可以使用 Xcode 内置的版本控制工具。

初次发布时，初始化 Package 为 Git 仓库，打上 Tag，再推送至远程仓库。

更新 Package 后，打上新的 Tag，Push 即可。

使用 Package

添加

我们先移除上文中的工程 Biu_test 引入的本地 Package（Biu），然后在 Xcode 中选择 File > Swift Packages > Add Package Dependency…，输入 Package 地址（https://github.com/keisme/Biu），点击 Next 安装。

安装完成后，重新运行项目，结果与预期一致。

更新

如果需要更新 Package，选择 File > Swfit Packages > Update to Latest Package Versionse。

移除

在工程中找到 Swift Package Manager，移除相应的 Package。
SwiftUI 教程 1.6 自定义 Modifier
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

自定义 Modifier

SwiftUI 提供了许多内建的 Modifier（修饰器），我们可以方便地调用。但是系统提供的有一定的局限性，如果我们需要自定义 Modifier，该如何实现呢？

设想有如下需求场景：在某个用户的名字右边，如果他是 Vip，显示 Vip 标识，如果不是，显示开通会员的按钮。如果我们能自定义一个 isVip 这样的 Modifier 可以方便的调用和展示差异化视图，那该是极好的。

首先，我们要实现自定义的 Modifier，需要实现 ViewModifier 协议：

struct Vip: ViewModifier {

let isVip: Bool



func body(content: Content) -> some View {

HStack {

content

if isVip {

Text("Vip")

.font(.caption).bold()

.foregroundColor(.white)

.padding(3)

.background(Color.orange)

.cornerRadius(3)

} else {

Button {

// action

} label: {

Text("开通会员")

.font(.caption)

.foregroundColor(.white)

.padding(5)

.background(Color.blue)

.clipShape(Capsule())

}

.buttonStyle(BorderlessButtonStyle())

}

}

}

}

.buttonStyle(BorderlessButtonStyle()) 的作用是为了让按钮在列表中，只有按钮可以响应点击事件。

然后我们给 View 添加扩展：

extension View {

func isVip(_ isVip: Bool) -> some View {

self.modifier(Vip(isVip: isVip))

}

}

接下来我们就可以方便的使用了：

Text("Bruce").isVip(false)

// 或

Text("Bruce").isVip(true)
SwiftUI 教程 1.3 按钮等控件
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

Button

构建方法

Button 的构建主要有以下两种方法：

// 1、字符串构建，支持本地化字符串

Button("Hello World") {

// action

} // 2、自定义样式

Button {

// action

} label: {

VStack(spacing: 8) {

Image(systemName: "square.and.arrow.up")

Text("Share")

}

.padding()

.foregroundColor(.white)

.background(Color.blue)

.cornerRadius(10)

.shadow(color: Color.black.opacity(0.35), radius: 5, x: 0, y: 5)

}

自定义 ButtonStyle

系统提供了六种 ButtonStyle，其中只有 DefaultButtonStyle 、 PlainButtonStyle 和 BorderlessButtonStyle 是用于 iOS 系统的。但是我们可以通过以下两个协议自定义样式：

ButtonStyle ：支持自定义样式

：支持自定义样式 PrimitiveButtonStyle ：支持自定义样式和交互

这两个协议的定义几乎一样，唯一的区别是 ButtonStyle 内部有一个 Bool 类型的属性 isPressed ，而 PrimitiveButtonStyle 内部有一个 trigger() 方法供我们自己手动调用。

下面我们通过实例来加深了解，我们先定义一个遵循 ButtonStyle 协议的 ShadowButtonStyle，它可以给按钮添加带圆角的阴影，使按钮在按下时改变字体和背景。

如果一个视图内部有多个 Button，我们只需要在调用一次 .buttonStyle(ShadowButtonStyle())，系统会通过环境变量将该样式注入各个子视图。

struct ShadowButtonStyle: ButtonStyle {

func makeBody(configuration: Configuration) -> some View {

configuration.label

.foregroundColor(configuration.isPressed ? .gray : .white)

.padding()

.background(configuration.isPressed ? Color.purple : Color.blue)

.cornerRadius(10)

.shadow(color: Color.black.opacity(0.35), radius: 5, x: 0, y: 5)

}

} HStack {

Button("Hello") {}

Button("World") {}

}

.buttonStyle(ShadowButtonStyle())

然后我们定义一个遵循 PrimitiveButtonStyle 的 DoubleTapButtonStyle，它表示按钮受到双击时，才会触发点击事件。代码如下：

struct DoubleTapButtonStyle: PrimitiveButtonStyle {

func makeBody(configuration: Configuration) -> some View {

configuration.label

.gesture(TapGesture(count: 2).onEnded { configuration.trigger() })

}

} Button("Double Tap") { print("Tapped ") }

.foregroundColor(.white)

.padding()

.background(Color.blue)

.cornerRadius(10)

.buttonStyle(DoubleTapButtonStyle())

EditButton

系统提供了一个快速构建编辑功能的按钮：EditButton ，它的功能和使用场景比较单一，按下的时候会进入编辑状态，按钮文字变成 “Done” ，再次按下变回 “Edit”，主要和 List 配合使用，通常这样调用： .navigationBarItems(trailing: EditButton()) 。

Menu

构建方法

Menu 用于快速构建菜单视图，有如下两种构建方法：

// 1、字符串构建

Menu("More") {

Button("Add") {}

Button("Edit") {}

Button("Delete") {}

} // 2、自定义构建

Menu {

Button {} label: {

Label("Add", systemImage: "plus")

}



Button {} label: {

Label("Edit", systemImage: "pencil")

}



Button {} label: {

Label("Delete", systemImage: "minus.circle")

}



// 只要是 View 类型皆可，这里使用了 Picker

Picker("Picker", selection: $selection) {

Text("Item1").tag(0)

Text("Item1").tag(1)

Text("Item1").tag(2)

}

} label: {

Text("More")

Image(systemName: "ellipsis")

}

自定义 MenuStyle

遵循 MenuStyle 协议并实现相应的方法，样例代码如下：
Creating Neuromorphic Designs in SwiftUI
Tags: Swift, Swiftui, Neuromorphic, iOS, Programming

Neuromorphic Design in SwiftUI

Color sets

To your project’s assets folder, add three new color sets by clicking the + sign. Below, we are going to add colors for both dark and light mode:

Make your first color set and name it mainColor . This color set is for the background and UI elements. The hex color value for the light color is #EFEEEE and #1F242F for the dark color.

The second color set is for the top-left shadow. The hex color value for the light color is #FFFFFF and #292D38 for the dark color.

The last color set is going to be for the bottom-right shadow. The light color hue is #D1CDC7 and the dark color is #14151C.

SwiftUI code

Below, I created a container for our neuromorphic design by using ViewBuilder . You can see in the code how and where to use the colors. You can adjust the shadow radius to your liking:

We can test the design with the simple code below:
SwiftUI 教程 1.4 选择器. 本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul…
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Slider

Slider 绑定的数据类型必须是浮点型，它的滑动范围默认是 0 到 1。

如下我们生命绑定数据的默认值是 0.5，然后生成一个 Slider 实例。

@State private var value: CGFloat = 0.5

​

Slider(value: $value)

我们也可以指定滑动范围，比如：

Slider(value: $value, in: 0.1...1)

给最值添加 Label：

Slider(value: $value, in: 0.5...1, minimumValueLabel: Text("0.5"), maximumValueLabel: Text("1)")) {}

指定步进值（step）：

Slider(value: $value, in: 0...1, step: 0.2) {}

初始化方法提供的 onEditingChanged 回调可以监听值的改变。

.accentColor(Color?) 可以改变滑竿的颜色。

示例代码：

Slider(value: $value, in: 70...147, step: 1, onEditingChanged: {

isEditing = $0

}, minimumValueLabel: Text("70"), maximumValueLabel: Text("147")) {

Text("Points")

}

.footnote("Points: \(value), is changing: \(isEditing)")

.accentColor(.orange)

Stepper

类似 Slider ，使用简单，不再赘述。

示例代码：

Stepper(value: $shoes, in: 2...20, step: 2) {

Text("Pair of shoes: \(shoes/2)")

}

ColorPicker

SwiftUI 提供了高度集成的颜色选择器：

ColorPicker(selection: $selectedColor, supportsOpacity: false) {

Label("Apple Color", systemImage: "applelogo")

.foregroundColor(selectedColor)

}

示例代码所示是通过自定义的 View 构建视图，当然我们也可以通过字符串快速构建视图，这里略过。 supportsOpacity 默认是 true，可以设置透明度，这里我们显式设置为 false。通过选择颜色，我们可以改变 Label 中的苹果 logo 和文字的颜色。
SwiftUI 教程 1.9 SwiftUI 中的属性包装器
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

常用属性包装器

SwiftUI 提供了许多的属性包装器（Property Wrapper），极大简化了我们的工作。属性包装器，实际上是对声明的属性做了一层封装，在内部实现了一些我们看不见的操作。

下面会在概念和使用上简介 SwiftUI 中常用的属性包装器，不在代码层面做具体演示。更详细的内容可以参见我的两篇文章：

@State

在当前 View 中声明，通常使用 private 修饰，当修饰的属性值改变时，界面会随之更新。

@Binding

接收从外部对象传入的绑定值，同时可以将属性的变化回传给外部对象，即数据是双向绑定的。如 A 的属性 @State private var value: String 传入 B 的属性 @Binding var value: String ，当 B 中的 value 值改变时， A 的 value 也会更新。

@Environment

访问预设的环境变量，如系统的暗黑模式、时区等。

@ObservedObject、@Published

@ObservedObject 可以修饰遵循 ObservableObject 协议的 class 对象，该对象实例中的属性可以使用 @Published 修饰。当使用 @Published 修饰的属性值发生改变时，所有使用 @ObservedObject 修饰的对象实例，都会更新相应的值，通常用于在多个界面之间同步数据和状态。

@StateObject

与 @ObservedObject 一样，@StateObject 修饰的对象同样是遵循 ObservableObject 协议的 class 对象。但是区别在于，@StateObject 修饰的对象只会在所属的 View 中创建一次并在 View 的生命周期内存储相应的状态，而 @ObservedObject 修饰的对象会随着 View 的重绘生成新的对象，不会在 View 的生命周期内存储该对象的状态。

@EnvironmentObject

@EnvironmentObject 修饰的对象同样需要遵循 ObservableObject 协议，与 @ObservedObject 功能类似，但是它有着更强大的功能，子视图可以直接获取父视图注入的环境变量。比如，我们有视图 A、B、C，A 包含 B，B 包含 C，如果我们使用 @ObservedObject 来传递变量，需要从 A 传入 B，再从 B 传入 C，C 才能获取到对应的变量。而 @EnvironmentObject 无需如此繁琐，我们直接通过父视图 A 注入环境变量，视图 C 就可以获取注入的变量，省去中间的传递过程。

@AppStorage

等同于 Userdefaults。

@SceneStorage

用于多窗口模式，相当于为每个场景持久化了一个场景值，每个场景只能读取该场景持久化的值。当场景销毁时，该值也会销毁。建议存储轻量的、不敏感的数据

@UIApplicationDelegateAdaptor

用来调用 AppDelegate 中的生命周期方法。

自定义属性包装器

使用属性包装器可以使我们的代码精简，那么如何根据需求自定义呢？

自定义的属性包装器需要使用 @propertyWrapper 声明，并且必须有一个名为 wrappedValue 的属性。例如下面的代码，通过 CNNumber 这样一个属性包装器，可以将字符串中的阿拉伯数字转化成中文数字：

@propertyWrapper

struct CNNumber {

private let table = [

"0" : "〇",

"1" : "一",

"2" : "二",

"3" : "三",

"4" : "四",

"5" : "五",

"6" : "六",

"7" : "七",

"8" : "八",

"9" : "九",

]



private var value = ""



var wrappedValue: String {

get { value }

set { value = convertToCNNumbers(newValue) }

}



init(wrappedValue: String) {

self.wrappedValue = wrappedValue

}



func convertToCNNumbers(_ string: String) -> String {

var res = ""

for v in string {

res += table[String(v)] ?? ""

}

return res

}

}

然后我们定义一个 Person 结构体，使用 CNNumber 去修饰 birth 属性，调用时正如示例所示，它被转换成了中文数字。

struct Person {

var name: String

@CNNumber var birth: String

} struct ContentView: View {

private let p = Person(name: "Steve Jobs", birth: "1955年2月24日")



var body: some View {

Text(p.birth)

}

}
SwiftUI 教程 1.8 使用 UIKit
Tags: Swift, Tutorial, Swiftui, Apps, iOS

Eul

本文为 Eul 样章，如果您喜欢，请移步 AppStore/Eul 查看更多内容。 Eul 是一款 SwiftUI 教程类 App（iOS、macOS），以文章（文字、图片、代码）配合真机示例（Xcode 12+、iOS 14+，macOS 11+）的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI 相关的知识，使读者能快速掌握并在 iOS 开发中实践。

SwiftUI 目前仍然在发展中，相比古老而健壮的 UIKit，它过于年轻，在生产实践中尚不能独挑大梁，有时我们需要借助 UIKit 来实现 SwiftUI 无法实现的功能。

UIViewRepresentable

如果我们想使用 UISearchBar 这样的控件，可以通过 UIViewRepresentable 协议来实现。

struct SearchBarView: UIViewRepresentable {

func makeUIView(context: Context) -> UISearchBar {

let uiView = UISearchBar()

uiView.placeholder = "Input something..."

uiView.searchBarStyle = .minimal

return uiView

}



func updateUIView(_ uiView: UISearchBar, context: Context) {

uiView.text = searchText

}

}

makeUIView 只有在实例初始化的时候调用一次， updateUIView 会在视图更新的时候调用。

然后我们就可以调用 SearchBarView 了，但是这还不够，如果我们要获取实时获取搜索框的文字内容，该怎么办？在 UIKit 中，我们可以通过代理方法获取，接下来的问题就是怎么讲值传给 SwiftUI。

UIViewRepresentable 协议中有个方法： func makeCoordinator() -> Self.Coordinator ，我们通过这个方法，可以实现将 UIKit 的变化传出去告诉 SwiftUI。我们只需要实现一个中间调度器，然后在这个方法内实例化调度器，并带上需要传给 SwiftUI 的内容即可。最后实现的所有代码如下：

struct SearchBarView: UIViewRepresentable {

@Binding var searchText: String



class Coordinator: NSObject, UISearchBarDelegate {

var searchBarView: SearchBarView



init(_ searchBarView: SearchBarView) {

self.searchBarView = searchBarView

}



func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

searchBarView.searchText = searchText

}



func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

searchBar.endEditing(true)

}

}



func makeCoordinator() -> Coordinator {

Coordinator(self)

}



func makeUIView(context: Context) -> UISearchBar {

let uiView = UISearchBar()

uiView.placeholder = "Input something..."

uiView.searchBarStyle = .minimal

uiView.delegate = context.coordinator

return uiView

}



func updateUIView(_ uiView: UISearchBar, context: Context) {

uiView.text = searchText

}

}

UIViewControllerRepresentable

UIViewControllerRepresentable 与 UIViewRepresentable 类似，只不过它的使用场景是使用控制器。这里简单举例如何使用：

struct SafariView: UIViewControllerRepresentable {

let url: URL



func makeUIViewController(context: Context) -> SFSafariViewController {

let controller = SFSafariViewController(url: url)

return controller

}



func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) {



}

}