前言
如何實現一張圖片在iPhone和iPad上顯示不同的尺寸,我了解到一般有三種辦法:直接手寫代碼動態添加約束;把NSLayoutConstraint關聯到ViewController里再viewDidLoad里面加判斷賦值;用size classes(這個目前還不太會)。這里分享一個直接在Storyboard里面就適配的辦法。
聲明
歡迎轉載,但請保留文章原始出處:)
博客園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.com
正文
import Foundation
class NSLayoutConstraintEx: NSLayoutConstraint {
@IBInspectable
var ipad: CGFloat = 0 {
didSet {
if DeviceUtils.isIPad() {
constant = ipad
}
}
}
@IBInspectable
var iphone4: CGFloat = 0 {
didSet {
// 640 x 960
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 960.0 {
constant = self.iphone4
}
}
}
@IBInspectable
var iphone5: CGFloat = 0 {
didSet {
// 640 x 1136
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 1136.0 {
constant = self.iphone5
}
}
}
@IBInspectable
var iphone6: CGFloat = 0 {
didSet {
// 750 x 1334
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 1334.0 {
constant = self.iphone6
}
}
}
@IBInspectable
var iphone6Plus: CGFloat = 0 {
didSet {
// 1242 x 2208
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height >= 1920.0 {
constant = self.iphone6Plus
}
}
}
}
class NSLayoutConstraintEx: NSLayoutConstraint {
@IBInspectable
var ipad: CGFloat = 0 {
didSet {
if DeviceUtils.isIPad() {
constant = ipad
}
}
}
@IBInspectable
var iphone4: CGFloat = 0 {
didSet {
// 640 x 960
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 960.0 {
constant = self.iphone4
}
}
}
@IBInspectable
var iphone5: CGFloat = 0 {
didSet {
// 640 x 1136
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 1136.0 {
constant = self.iphone5
}
}
}
@IBInspectable
var iphone6: CGFloat = 0 {
didSet {
// 750 x 1334
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height == 1334.0 {
constant = self.iphone6
}
}
}
@IBInspectable
var iphone6Plus: CGFloat = 0 {
didSet {
// 1242 x 2208
if DeviceUtils.isIphone() && DeviceUtils.getScreenSize().height >= 1920.0 {
constant = self.iphone6Plus
}
}
}
}
用法:
修改現在的約束,讓它使用NSLayoutConstraintEx,效果如下:
注意User Defined Runtime Attributes這一欄,如果去掉某個自定義屬性,這邊可能會存在殘留,刪掉殘留的那一項即可。還有Module這一欄如果顯示None說明使用自定義類失敗,一般把Class刪除一下重新制定就好了。
默認是iPhone布局,這樣在iPad上就能使用大尺寸的圖片了
結束
買了本Auto Layout開發秘籍,繼續學習和思考屏幕適配方面的內容。