![](/img/trans.png)
[英]Swift Protocol Extension with AssociatedType Constrained to Collection, Can't Use Subscript
[英]Swift: Can't use mutating method in Protocol Extension
我有4個視圖控制器,需要根據用戶屏幕寬度使用不同的圖像。 我正在嘗試保持代碼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
以便使用。
這段代碼:
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
}
不合法 最主要的是擴展不能添加新的存儲屬性-因此您不能這樣做:
let imageToUse = setupBG()
在擴展中。
另外,這一行:
imageView.image = image
在func
之外是非法的。
至於您在這里需要什么,這一切似乎都不過分。 為什么要使用協議將其擴展到viewControllers? 您有一個返回imageName的函數-可以在任何地方(只是免費的func,不在類中)。
然后,在viewControllers中,只需將圖像視圖的圖像設置為此函數返回的名稱即可。
擴展是為類提供更多接口的一種方法-您不能使類僅通過擴展自動調用方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.