ユーザーの画面の幅に基づいて別のイメージを使用する必要がある4つのView Controllerがあります。私はコードDRYを維持し、プロトコル拡張を使用しようとしています。スイフト:プロトコル拡張で突然変異法を使用できません
以下は私のプロトコルです:
import UIKit
enum ScreenWidths: CGFloat {
case iPhone455s = 320.0
case iPhone6 = 375.0
case iPhone6Plus = 414.0
}
protocol ScreenSizeProtocolExt {
mutating func setupBG() -> String
}
extension ScreenSizeProtocolExt {
mutating func setupBG() -> String {
let imageName: String
let userScreenWidth = UIScreen.mainScreen().bounds.width
switch userScreenWidth {
case ScreenSizeWidth.iPhone455s.rawValue:
imageName = "imageA"
case ScreenSizeWidth.iPhone6.rawValue:
imageName = "imageB"
case ScreenSizeWidth.iPhone6Plus.rawValue:
imageName = "imageC"
default:
imageName = "imageAll"
}
return imageName
}
}
は今、私はそれを使用しようとしています:
extension myViewController: ScreenSizeProtocolExt {
let imageToUse = setupBG()
// Here is get an error: 'Use of instance member 'setupBG' on type 'inout Self'; did you mean to use a value of type 'inout self' instead?
let image = UIImage(named: imageToUse)
imageView.image = image
}
はどのようにして画面の幅を検出し、右を私に提供するためのプロトコルの拡張機能を使用することができますimageName
使用する。
エクステンション内にフローティングコードを置くことはできません。メソッドに配置する必要があります – Hamish
コードを再利用しようとしています。私がプロトコルを適用しているコードを置くと、その目的を破るでしょう。 – user1107173
内の 'extension myViewController:ScreenSizeProtocolExt'プロトコル拡張によって返された正しい文字列に基づいてイメージを作成し、それをローカルのimageView変数に割り当てようとしています。 – user1107173