Swift /代码重构/如何将参数添加到UIView
问题描述:
我有以下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")
帮助是非常赞赏。
答
试试这个:
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
乐意帮忙:) –
答
如果你想避免破坏你的代码中的任何现有的实现,你可以使用默认参数的方法,做这样的事情:
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
非常感谢你的帮助和努力,但第一个答案基本上为我做了。 –
有关添加什么参数的方法? 'func addBackground(imageName:String)' –
请注意,这与编程语言中“generic”的一般含义无关。这更多的是介绍一个参数 - 这是一个非常基本的任务 - 你真正的问题是什么?只需为该函数添加一个参数即可。 – luk2302
我改变了标题。感谢您的关注。 –