여느 때랑 다름없이 사지방에 앉아서 코딩을 하고 있었다.
힘들어서 잠깐 쉬면서 이것저것 만지고 있었는데, 갑자기 맨날 보던 화면이 문득 이상하다는 생각이 들었다.
저 Hello World!가 왜 프리뷰 중앙에 있지??
좌측 코드를 보면 알겠지만, 나는 Text("Hello World!")
에게 위치를 특정해주는 어떠한 modifier(.position
, .offset
)도 사용하지 않았다. 그냥 Text
하나만 달랑 썼는데 자동으로 중앙으로 배치되어 있는 것이다.
물론 정서상(?)으로 중앙이 맞긴 하지만, 처음 코딩을 배울 때, 저 텍스트가 좌측 상단에 표시되었어도 전혀 이상하지 않았을 거 같다는 생각이 들었다.
나는 이런 화면 배치에 고의성이 느껴져서 정리된 내용이 있는지 찾아봤는데, 아니나 다를까 한국어로 정리된 글도 엄청 많고, 아예 WWDC에서 광고를 광고를 했는데도 나만 모르고 있었다.
이렇게 알게된 이 글의 주제는 바로 SwiftUI가 View의 레이아웃을 결정하는 과정이다.
뷰의 레이아웃을 결정하는 과정을 배우기 전에 먼저 뷰 계층(view hierarchy)에 관한 이해가 필요합니다.
이해를 위해 WWDC 19에 나온 간단한 뷰의 동작을 살펴보겠습니다.
아래 코드에는 3개의 뷰가 동작하고 있습니다.
뷰 계층의 맨 아래에는 Text
가 있고,
그 위에는 ContentView
가 있습니다.
이 때, 레이아웃 중립(Layout neutral)이라는 개념이 나오는데,
body
를 가진 모든 상위 뷰는 그들의 경계가 body
의 경계와 동일한 것을 말합니다.
쉽게 말하면, 뷰 레이아웃에 아무런 영향을 끼치지 않는 것이라고 이해해도 좋을 것 같습니다.
위 예시에서는 body
를 가진 ContentView
를 레이아웃 중립이라고 부르고, 실제로 body
와 ContentView
는 동일한 경계를 가지고 있습니다.
그래서 예시 이미지 우측에 표시되는 경계가 Text
와 같음을 볼 수 있습니다.
그리고 그 위엔 Root View
가 있습니다.
레이아웃 중립인 ContentView
는 Text
와 같은 경계를 나타내기 때문에 생략하고 위처럼 표현할 수 있습니다.
레이아웃을 결정하는 원칙은 크게 3단계로 구성됩니다.
1.
Parent View
가Child View
에게 사이즈를 제안한다.
2.Child View
는 자신의 사이즈를 결정한다.
3.Parent View
는Child View
를 자신의 좌표 공간에 배치한다.
Parent View
는 뷰 계층에서 상대적으로 상위에 있는 뷰를 말하고,
Child View
는 뷰 계층에서 상대적으로 하위에 있는 뷰를 말합니다.
뷰 계층의 최상단에 위치한 Parent가 Child에게 차례차례 사이즈를 제안해옵니다.
예시에서는 Parent View
인 Root View
가 Child View
인 Text
에게 사용 가능한 모든 영역을 제안합니다.
하지만 Text
는 제안된 영역을 다 사용하는게 아니라 자신에게 필요한 영역만 선택합니다. 위 예시에서는 Hello World가 들어갈 수 있는 공간만을 차지하겠다고 응답합니다.
그리고 SwiftUI에서는 이런 Child View
의 size를 강제할 수 있는 방법이 없기 때문에 Parent View
는 이 결정을 들어 주어야만 합니다.
Root View
는 크기를 결정한 Text
를 자신의 공간에 중앙에서부터 배치합니다. >> 내 궁금증은 이거였는데, 크게 특별한 이유는 없었다.(ㅠㅠ)
SwiftUI의 모든 레이아웃은 위 과정을 통한 Parent와 Child의 상호작용으로 나타나게 됩니다.
세 개의 원칙 중에서 두 번째 과정에서 Text
가 자신에게 필요한 사이즈를 String의 크기를 고려해 결정한 것처럼 각 뷰들은 자신의 사이즈를 조절하는 방법 및 시기를 결정할 수 있습니다.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.foregroundColor(.accentColor)
Text("Hello world!")
.background(Color.red)
}
}
}
위 예시 코드의 뷰 계층을 그려보면 Text
와 Image
에 modifier들이 있어서 기존 원칙을 어떻게 적용해야할지 고민되는데, modifier 역시 뷰 계층에 적용됩니다.
애플 공식 문서를 보면 modifier를 이렇게 정의하고 있습니다.
modifier(_:)
뷰에 modifier를 적용해서 새로운 뷰를 리턴한다.
그리고 예시에 적용된 foregroundColor
와 background
의 문서를 확인해보면 역시 리턴 타입이 View
인걸 확인할 수 있습니다.
결국 이 modifier들이 새로운 뷰를 반환하니까 그 뷰도 화면에 그려지기 위해서는 앞서 설명한 원칙을 지켜야합니다. 위 예시에서 modifier를 고려한 뷰 계층은 다음과 같습니다.
background
modifier는 Color
뷰를 secondary child로 갖습니다. 이 뷰는 Text
뷰의 사이즈가 결정되면, 그 경계까지만 적용됩니다.
이제 레이아웃 원칙을 고려하면서 레이아웃 결정 과정을 살펴보기 전에!!
여러 뷰를 담고 있는 VStack
이 레이아웃을 결정할 때 일어나는 과정을 이해하면 전체적인 과정을 이해하기 좀 더 쉬워집니다.
HStack, VStack은 Parent에게 제안받은 사이즈를 일련의 과정을 거쳐서 자식뷰들에게 제안합니다.
VStack이 부모에게 400x400의 크기를 제안받았다고 가정해보겠습니다.
1. Child View들끼리 가지는 spacing의 크기만큼 Parent에게 제안받은 사이즈에서 뺀다.
위 예시에서는 Image
와 Text
사이의 spacing이 될 것입니다. spacing이 20이라면 VStack은 제안받은 400에서 20을 뺀 380을 Child View들에게 제공하는 것입니다.
2. Child View의 수만큼 영역을 똑같은 크기로 나눈다.
위 예시에서 Child View가 2개 이므로 400x380을 400x190으로 나눕니다.
(VStack이니 가로 너비는 나누지 않습니다.)
3. 우선순위가 높은 Child View부터 사이즈를 제안합니다.
우선순위가 정해지지 않았다면 가장 경직적인 뷰부터 제안을 받습니다. Image
는 특정 modifier들이 없으면 자신의 크기를 항상 고정시키기에 경직적이라고 말합니다.
4. 모든 Child View의 사이즈가 결정되면 처음에 계산했던 spacing과 함께 Child View들을 정렬한다.
정렬기준을 미리 정해주지 않을경우 center로 정렬합니다.
5. 자신의 크기를 Child View들을 수용할 정도로만 결정하고 Parent에게 응답한다.
자세한 건 후에 다루기로 하고, 이제 위 예시의 레이아웃 과정을 살펴보겠습니다.
Root View
가 ContentView
에게 사이즈를 제안합니다.ContentView
는 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 VStack
에게 다시 제안합니다.VStack
은 앞서 설명한 과정을 거치고 경직적인 Image
에게 먼저 사이즈 제안을 합니다.Image
foregroundColor
는 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 Image
에게 제안합니다.Image
는 자신의 크기를 결정하고 상위 뷰에게 알립니다.foregroundColor
는 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 VStack
에게 제안합니다. 추가적으로foregroundColor
는 SwiftUI 에게 Image
의 색을 자신이 정한 색으로 렌더링 하도록 말합니다.Text
background
는 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 Text
에게 제안합니다.Text
는 자신에게 필요한 크기를 정하고(Hello, world!만큼의 크기) 상위 뷰에게 알립니다.background
는 사이즈를 상위 뷰에게 알리기 전에, 자신의 Secondary Child인 Color
에게 사이즈를 제안합니다. Color
역시 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 하위 뷰에 전달하려고 하지만, Color
는 하위 뷰가 없습니다. 이렇게 뷰 계층에서 완전히 레이아웃 중립인 경우, 사용 가능한 모든 공간을 차지합니다.Color
의 사이즈가 정해졌으므로, background
는 자신의 중간에 Color
를 배치합니다. 그리고 자신의 사이즈를 VStack
에게 알립니다.VStack
은 두 개의 하위 뷰에서 받은 사이즈와 정해놓은 spacing의 크기를 종합해 자신의 사이즈를 정하고, ContentView
에게 알립니다.ContentView
는 레이아웃 중립이기 때문에, 제안받은 사이즈를 그대로 Root View
에게 다시 제안합니다.Root View
는 ContentView
를 자신의 공간의 중앙에 배치합니다.맨날 보던 화면에서 이런 디테일이 숨어있을거라곤 생각도 못했다. Swift나 SwiftUI를 이제 어느정도 안다고 생각하고 있었는데, 이번 경험을 통해 내가 인지못하고 있는 무언가들이 많을 거라고 느꼈다. 코딩은 알게 되면 알게될수록 겸손해지는 것 같다.😶🌫️
Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. pool cover
I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates. Seo company
Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. event planner company
Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, Richardson sober living
That you're allowed to place leaders, however is not one way links, except when they're just authorised together with regarding niche. Result Macau 5D
Bless you designed for presenting modern up-dates concerning the anxiety, As i watch for browse alot more. agenolx daftar
I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. 아이디판매
Great article, Thanks a lot pertaining to expressing This specific know-how. Outstandingly prepared content, only when most web owners presented a similar a higher level written content because you, the world wide web has to be superior position. Remember to continue! abonnements Iron Pro TV
I know this is one of the most meaningful information for me. And I'm animated reading your article. But should remark on some general things, the website style is perfect; the articles are great. Thanks for the ton of tangible and attainable help. idr168 login
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanksidr168 link alternatif
Awesome post. Typically the put up can affect a considerable amount of instant concerns our the community. We tend to can't be uninvolved towards such concerns. This unique put up will provide good ideas not to mention strategies. Especially instructive not to mention efficient. Hi88 Institute
What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. Hognose snake
【 얌얌티비 】스포츠무료중계,MLB중계,스포츠중계,해외축구중계,NBA중계,축구중계,야구중계,메이저리그중계,농구중계,메이저스포츠방송,실시간중계,느바중계,중계,티비중계,스포츠실시간,무료티비,이피엘중계,EPL중계,스포츠실시간 | 얌얌티비 해외축구중계
Whenever I have some free time, I visit blogs to get some useful info. Today, I found your blog with the help of Google. Believe me; I found it one of the most informative blog. slack meeting
Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. ดูบอลสดpptv36
You have a good point here!I totally a demo slot olympusgree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!empire88
Today, I was just browsing along and came upon your blog. Just wanted to say good blog and this article helped me a lot, due to which I have found exactly I was looking.وان ایکس بت فارسی
Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. bitumen 60/70 in bag
I just astounded aided by the test most people made to choose this specified share wonderful. Marvelous recreation!
I just astounded aided by the test most people made to choose this specified share wonderful. Marvelous recreation! 슬롯커뮤니티
It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing. betforward بدون فیلتر
Within the other hand, no matter how nice being and treating any rig, ultimately it easy to see an incident in the place you must do any help controlling; yet conditioned on how old you are but physical exercise, with all the body for your caravan it is a particularly excessive physical activity. motor movers login lotus33
Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. sms
Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. วิเคราะห์บอล วันนี้
Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. ทีเด็ดบอลวันนี้: คัดสรรคู่เด็ดเพื่อคุณ
This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. Thruster finance
I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. kitchen radiators
I felt very happy while reading this site. This was really very informative site for me. I really liked it. This was really a cordial post. Thanks a lot!. rtp duatoto
Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best.
Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best.BPC 157 TB 500
I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work.Peptides for weight loss
The post is written in very a good manner and it contains many useful information for me. bandar toto macau
With thanks to get furnishing recently available posts in connection with the dilemma, I actually look ahead to learn extra. 대전출장마사지
You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. 아이허브 할인코드 You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. 슬롯사이트 You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. 밤알바 You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. 아고다할인코드
Thanks for this great post, i find it very interesting and very well thought out and put together. I look forward to reading your work in the future. 박스폰 매입
Outstanding submit, travelled in advance and also book marked your internet site. My partner and i can’t hold out to learn a lot more coming from an individual. เว็บพนันออนไลน์ 888 เว็บตรง
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. 안전놀이터추천
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. 롤대리
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. https://heally.co.kr/
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! 안전놀이터추천
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! 롤대리
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! https://heally.co.kr/
My spouse and i shocked while using investigation anyone created to choose this certain release outstanding. Amazing task!Suscripción IPTV
Your own songs is actually incredible. You've a few really gifted designers. We desire a person the very best associated with achievement. 한게임머니상
You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. 롤대리
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Learn More
Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. macau 4D
You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... shtepi ne shitje
Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. https://jgtv24.com
I’m encouraged while using surpassing along with preachy list that you just adorn such minor timing. 카지노 솔루션
Fantastic submit, Many thanks regarding revealing This kind of information. Fantasticly composed write-up, only if almost all people supplied the identical amount of articles when you, the net would have been a greater spot. You should keep writing! 토토솔루션
Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. cbridge
You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. 슬롯분양
Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. Comprehensive Check Cashing Overview
The post is written in very a good manner and it contains many useful information for me. สล็อต
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. kinggame
Recently, I have commenced a blog the info you give on this site has encouraged and benefited me hugely. Thanks for all of your time & work. PC방 대리
Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. 토토사이트
Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. situs slot
Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. เว็บตรง
Jeanette’s Cakes provides top-tier cakes and desserts, all made with the freshest natural ingredients. Perfect for any event, our treats make every moment sweeter. Enjoy our baking lessons, parties, and team-building activities. Custom cakes ontario
Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. 무료 스포츠 중계
I’m not sure exactly how I discovered your blog because I had been researching information on Real Estate in Lake Mary, FL, but anyway, I have had a pleasant time reading it, keep it up! 챔스 중계
Play over 5000 exciting games at LUXYPLAY Casino, including live casino and sports betting. With fair play, daily bonuses, and big prizes, you’re in for an unforgettable gaming experience. Free bonus
Wow, excellent post. I'd like to draft like this too - taking time and real hard work to make a great article. This post has encouraged me to write some posts that I am going to write soon. 슬롯무료체험
I've lately began the weblog, the data a person supply on this website offers assisted me personally significantly. Many thanks with regard to all your period & function. 010인증대행
I just now idea it can be a notion to share incase anybody else seemed to be experiencing difficulty investigating although My business is a bit undecided plainly was allowed to fit bands in addition to deals with with in this article.일산명월관
Recently, I have commenced a blog the info you give on this site has encouraged and benefited me hugely. Thanks for all of your time & work. 해상직구
Your work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.MyPrivate IPTV UK
Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. 삼척 가라오케
We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. 총판커뮤니티
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. 총판월드
Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. télécharger 1xbet gratuit
I would like to say that this blog really convinced me to do it! Thanks, very good post.small business
I read a article under the same title some time ago, but this articles quality is much, much better. How you do this.. situs toto slot
You have outdone yourself this time. It is probably the best, most short step by step guide that I have ever seen. https://museeduscaphandre.com/
Modern Specialized University is apioneering and accredited educational institution that aims to prepare specialized and highly qualified scientifically and technologically in line with the progress and cognitive development to contribute to the national development process. It aims also to strengthen community participation and sustainable development across all sectors and groups of society. The University is also constantly updating to keep up with the accelerated development in the field of education and research on a permanent basis Yemen
Kantorbola adalah situs gaming online terbaik di indonesia , kunjungi situs RTP kantor bola untuk mendapatkan informasi akurat rtp diatas 95% . Kunjungi juga link alternatif kami di kantorbola77 dan kantorbola99 kantor bola
The website is easy to navigate, allowing visitors to find the information they need quickly and efficiently, enhancing the user experience.
The posts inspire readers to think deeply about their own experiences and apply the lessons shared to their personal situations. https://dailylifeprayer.org/
Your blog is too much amazing. I have found with ease what I was looking. Moreover, the content quality is awesome. Thanks for the nudge! bandar toto macau
Good artcile, but it would be better if in future you can share more about this subject. Keep posting. 大阪市中央区 不妊治療
It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing. เว็บสล็อต
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. 다낭가라오케
Each post motivates individuals to embrace challenges as opportunities for personal development. https://dailylifeprayer.org/prayer-for-ex-love-back/
Hey, I am so thrilled I found your blog, I am here now and could just like to say thank for a tremendous post and all round interesting website. Please do keep up the great work. I cannot be without visiting your blog again and again. Make1M.com
I think this is an informative post and it is very beneficial and knowledgeable. Therefore, I would like to thank you for the endeavors that you have made in writing this article. All the content is absolutely well-researched. Thanks... download siterips enhance upscale
Superior post, keep up with this exceptional work. It's nice to know that this topic is being also covered on this web site so cheers for taking the time to discuss this! Thanks again and again! togel online
What is DexScreener and how do you use it in crypto trading