2017-08-03 188 views
1

我已經給出了標籤,並給出了XY軸的值,但是我的值沒有在每個設備的中心放置標籤,並且如果設備大設置,我寫了寬度大小的方法寬度大小50更小,但這種方法不適用於iPhone SE,5S/5,6/6s/7,僅適用於iPhone 6 +/6S +/7 +!例如像這樣Swift 3 - 設置每個設備的XY軸UILabel

enter image description here

那麼,什麼是錯的,我應該補充什麼補充?

let lengthOfChar : CGFloat = data.ans.length // Characters form SQLite database 
let yAxis : CGFloat = self.view.frame.height/3 * 1.8 
let width: CGFloat = view.frame.size.width - 40 // frame width 
var targetWidth: CGFloat = (width - (lengthOfChar - 1) * 5)/lengthOfChar 

if targetWidth > 50 { 
    targetWidth = 50 
} 

let totalWidth: CGFloat = (targetWidth * lengthOfChar) + ((lengthOfChar - 5) * 5) 
let x : CGFloat = (width/2) - (totalWidth/2) 
let xx : CGFloat = (CGFloat(indexTar) * targetWidth) + (CGFloat(indexTar) * 5) + 20 
var xAxis : CGFloat = (x + xx) 
xAxis = width - xAxis 
+2

使用auto.layout和約束它更容易和非常強大 – Phyber

+0

它可能會更容易讓你使用自動佈局 – YoCoh

+0

我ca不是因爲我的項目由代碼創建,我無法返回項目@Phyber –

回答

0

我使用的幫助枚舉允許爲某些iPhone定製事物。安裝枚舉使用下面。

添加新類與此代碼:

enum DeviceType: Int { 
    case iPhone4 = 1 
    case iPhone5 
    case iPhone6 
    case iPhone6Plus 
    case iPad 

    init(userInterfaceIdiom: UIUserInterfaceIdiom, screenHeight: CGFloat) { 
    switch (userInterfaceIdiom, screenHeight) { 
    case (.phone, 0..<568.0): 
     self = .iPhone4 
    case (.phone, 568.0..<667.0): 
     self = .iPhone5 
    case (.phone, 667.0..<736.0): 
     self = .iPhone6 
    case (.phone, 736.0..<CGFloat.infinity): 
     self = .iPhone6Plus 
    case (.pad, _): 
     self = .iPad 
    default: 
     self = .iPhone6 
    } 
    } 

    func isSameOrSmaller(than deviceType: DeviceType) -> Bool { 
    return self.rawValue <= deviceType.rawValue 
    } 
} 

使用

if UIDevice.current.type().isSameOrSmaller(than: .iPhone5) { 
    // Do what you need 
} 
+0

使用自動佈局要容易得多。 – Phyber

+0

@Phyber似乎他需要做一些自定義的東西 –

+0

如何在我的函數中在ViewController中調用此代碼? @TungFam –

0

在代碼中使用自動佈局

label.translatesAutoresizingMaskIntoConstraints = false 

label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true 
label.heightAnchor.constraint(equalToConstant: 40).isActive = true 
label.widthAnchor.constraint(equalToConstant: 150).isActive = true 
label.topAnchor.constraint(equalTo: self.purpleBox.bottomAnchor, constant: 20).isActive = true 

你可以做任何你想要它。這非常強大。

其他一些錨可以使用

// centerYAnchor 
// leftAnchor 
// rightAnchor 
// bottomAnchor 

對於進一步閱讀:Working with Layout anchors

-1

我解決我的問題,這樣的解決方案:

postfix operator % 

postfix func % (percentage: CGFloat) -> CGFloat { 
    return (CGFloat(percentage)/100) 
} 

let yAxis : CGFloat = (self.view.frame.height) * 60% 

if lengthOfChar >= 8 { 

    targetWidth = 40 

} else { 

    targetWidth = 50 

} 
+0

看到這個解決方案,我很高興給你提供反饋給我:) @TungFam –

+0

看到這個解決方案,我很高興給你提供反饋給我:) @Phyber –

+0

我很高興這對你有效,但硬編碼屏幕的高度和寬度是非常脆弱的,真的不應該這樣做。 – Abizern