Swift - 重复的 UIView
Posted
技术标签:
【中文标题】Swift - 重复的 UIView【英文标题】:Swift - Duplicate UIView 【发布时间】:2018-11-01 10:31:57 【问题描述】:我目前正在尝试在 Swift 中实现微光效果。为此,我创建了一个灰色 UIView,并在其上创建了另一个具有效果的 UIView。 问题是我写了两次相同的代码......
let profileShimmerView = UIView()
profileShimmerView.backgroundColor = whiteClear
profileShimmerView.layer.cornerRadius = 20
profileShimmerView.clipsToBounds = true
let profileView = UIView()
profileView.backgroundColor = grayClear
profileView.layer.cornerRadius = 20
profileView.clipsToBounds = true
self.addSubview(profileView)
self.addSubview(profileShimmerView)
profileShimmerView.translatesAutoresizingMaskIntoConstraints = false
profileShimmerView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45).isActive = true
profileShimmerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15).isActive = true
profileShimmerView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileShimmerView.heightAnchor.constraint(equalToConstant: 40).isActive = true
profileView.translatesAutoresizingMaskIntoConstraints = false
profileView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45).isActive = true
profileView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15).isActive = true
profileView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileView.heightAnchor.constraint(equalToConstant: 40).isActive = true
有没有更简单的方法来实现这一点?
【问题讨论】:
你为什么不继承UIView
并设置所有需要设置的变量以在你的子类的初始化程序中实现微光效果?
可能需要一个函数来重用?
【参考方案1】:
你可以创建一个函数
func shared(color : UIColor)->UIView
let v = UIView()
v.backgroundColor = color
v.layer.cornerRadius = 20
v.clipsToBounds = true
self.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
v.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 45),
v.topAnchor.constraint(equalTo: self.topAnchor, constant: 15),
v.widthAnchor.constraint(equalToConstant: 40),
v.heightAnchor.constraint(equalToConstant: 40)
])
return v
【讨论】:
以上是关于Swift - 重复的 UIView的主要内容,如果未能解决你的问题,请参考以下文章
Swift UIView.animateWithDuration [重复]
Swift 3:发送到实例 Xcode 8 的无法识别的选择器 [重复]