2016-03-04 31 views
-2

我有以下UIView擴展來添加背景。Swift /代碼重構/如何將參數添加到UIView

extension UIView { 
func addBackground() { 
    // screen width and height: 
    let width = UIScreen.mainScreen().bounds.size.width 
    let height = UIScreen.mainScreen().bounds.size.height 

    let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height)) 
    imageViewBackground.image = UIImage(named: "index_clear") 
    imageViewBackground.clipsToBounds = true 

    // you can change the content mode: 
    imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill 
    self.addSubview(imageViewBackground) 
    self.sendSubviewToBack(imageViewBackground) 
}} 

self.view.addBackground() 

什麼使通用的擴展的最佳實踐打電話了嗎?我想改變這樣的畫面:

self.view.addBackground("index_clear") 

self.view.addBackground("other_background_image") 

幫助是非常讚賞。

+0

有關添加什麼參數的方法? 'func addBackground(imageName:String)' –

+0

請注意,這與編程語言中「generic」的一般含義無關。這更多的是介紹一個參數 - 這是一個非常基本的任務 - 你真正的問題是什麼?只需爲該函數添加一個參數即可。 – luk2302

+0

我改變了標題。感謝您的關注。 –

回答

1

試試這個:

extension UIView { 
func addBackground(imgName : String) { 
    // screen width and height: 
    let width = UIScreen.mainScreen().bounds.size.width 
    let height = UIScreen.mainScreen().bounds.size.height 

    let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height)) 
    imageViewBackground.image = UIImage(named: imgName) 
    imageViewBackground.clipsToBounds = true 

    // you can change the content mode: 
    imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill 
    self.addSubview(imageViewBackground) 
    self.sendSubviewToBack(imageViewBackground) 
}} 
+0

完美的作品。非常感謝你我完全不知道語法 –

+0

樂意幫忙:) –

2

如果你想避免破壞你的代碼中的任何現有的實現,你可以使用默認參數的方法,做這樣的事情:

extension UIView { 
    func addBackground(imageName: String = "index_clear") { 
     // screen width and height: 
     let width = UIScreen.mainScreen().bounds.size.width 
     let height = UIScreen.mainScreen().bounds.size.height 

     let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height)) 
     imageViewBackground.image = UIImage(named: imageName) 
     imageViewBackground.clipsToBounds = true 

     // you can change the content mode: 
     imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill 
     self.addSubview(imageViewBackground) 
     self.sendSubviewToBack(imageViewBackground) 
    } 
} 


// You can continue to use it like so 
myView.addBackground() // uses index_clear 

// or 
myView.addBackground("index_not_clear") // uses index_not_clear 
+0

非常感謝你的幫助和努力,但第一個答案基本上爲我做了。 –