iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0
Software Development

Swift 學習目標 -- 30 天送審第一支APP系列 第 11

DAY 11: Auto Layout 定位方式

我們想把一個常用社群的 logo 放到 APP 裏頭。
首先,放置 asset 裡頭的圖片 logo 。

一開始我們會直覺的先用定位法,給定我們希望 logo 出現的位置。


let photoImage = UIImageView(image:#imageLiteral(resourceName: "001-snapchat-1"))
        view.addSubview(photoImage)
        
photoImage.frame = CGRect(x: 120, y: 30, width: 50, height: 50)

結果就如同我們所期待的。
https://ithelp.ithome.com.tw/upload/images/20171230/20107694Xq1ZK7h3hY.png

但是,假如我們把手機水平放置的時候, logo 的地方就會完全跑掉了。
並且,假如我們用 iphone X 上預覽這個畫面的話,結果更是難以想像。

解決的方式之一,就是使用 Auto Layout 取代絕對定位。
把先前的程式碼 comment 掉。

        // 1. set up the four constraints
        // 2. this enables autolayout
  photoImage.translatesAutoresizingMaskIntoConstraints = false
        // 3. then, set these four constraints to be active
  hotoImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
//photoImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 
//but now we want our logo close to the top
  photoImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
  photoImage.widthAnchor.constraint(equalToConstant: 50).isActive = true
  photoImage.heightAnchor.constraint(equalToConstant: 50).isActive = true

首先給出四個 constraints ,分別以 centerXAnchor , centerYAnchor , widthAnchor 及 heightAnchor 進行定位。

translatesAutoresizingMaskIntoConstraints 其中,AutoresizingMask 是一個讓元素 subView 依據他的 superView 自動變更大小的屬性。可以把它想像成是一組免費奉送的 contraints,預設值為true。在不修改預設值成 false 之前,我們將無法使用我們自己訂的 Auto Layout constraints。

最後,我們還需要把這四個 constraints 的 isActive 設為 true 。才會開始作用。


上一篇
DAY 10: 淺談 Swift 的錯誤處理
下一篇
DAY 12: Some more Auto Layout
系列文
Swift 學習目標 -- 30 天送審第一支APP33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
吳晉榮
iT邦新手 5 級 ‧ 2017-12-30 16:28:26

請問如果想要將一群UI元件做auto layout要怎麼處理呢?
只能一個一個獨立寫嗎?

使用 UIStackView 幫助你

我要留言

立即登入留言