有时我需要在Swift中创建相同的视图(或ImageViews)。
例如,制作相同的尺寸和图像,删除视图,然后再次制作(有时会更改视图的图像或大小)。
在这种情况下,当然每次编写相同的代码需要视图都不好。 所以我想找到多次创建相同视图的好方法。
现在我在创建相同的ImageView时使用此代码。
* CreateImage.swift
class aImageView: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
let aImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 50))
aImageView.image = UIImage(named: "item_a01_70x50")
aImageView.tag = 100
aImageView.isUserInteractionEnabled = true
aImageView.backgroundColor = UIColor.lightGray
self.addSubview(aImageView)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
class bImageView: UIImageView {
override init(frame: CGRect) {
super.init(frame: frame)
let bImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 50))
bImageView.image = UIImage(named: "item_b02_70x50")
bImageView.tag = 200
bImageView.isUserInteractionEnabled = true
bImageView.backgroundColor = UIColor.lightGray
self.addSubview(bImageView)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
* TopView.swift
class TopView: UIView {
var aview: aImageView!
var bview: bImageView!
init(frame: CGRect, stage:Int){
super.init(frame: frame)
aview = aImageView(frame :CGRect(x: 0, y: 0, width: 70, height: 50))
self.addSubview(aview)
bview = bImageView(frame :CGRect(x: 100, y: 100, width: 70, height: 50))
self.addSubview(bview)
//...and sometimes delete them, create them again other time, and create...
}
}
如果你知道更好的方式,你能告诉我吗?
感谢。
答案 0 :(得分:0)
答案 1 :(得分:0)
只定义一个类( ex:Utility.swift ),它将提供自定义视图。 添加子视图后,最后但并非最不重要的是自动布局(例如: aImageView )。 我正在遵循这种技术。
答案 2 :(得分:0)
我认为你可以像这样扩展UIImageView
:
extension UIImageView {
convenience init(_imageName: String = "",
_frameTulpe: (x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) = (0, 0, 0, 0),
_tag: Int = 0,
_isUserInteractionEnabled: Bool = true,
_backgroundColor: UIColor = UIColor.lightGray)
{
self.init(image: UIImage(named: _imageName))
frame = CGRect(x: _frameTulpe.x, y: _frameTulpe.y, width: _frameTulpe.w, height: _frameTulpe.h)
tag = _tag
isUserInteractionEnabled = _isUserInteractionEnabled
backgroundColor = _backgroundColor
}
}
然后,在TopView.swift
中将会是:
class TopView: UIView {
var aview: aImageView!
var bview: bImageView!
init(frame: CGRect, stage:Int){
super.init(frame: frame)
aview = UIImageView(_imageName: "item_a01_70x50", _frameTulpe:(0, 0, 70, 50), _tag: 100)
self.addSubview(aview)
bview = UIImageView(_imageName: "item_b02_70x50", _frameTulpe:(100, 100, 70, 50), _tag: 200)
self.addSubview(bview)
//...and sometimes delete them, create them again other time, and create...
}
}