Swift-重复的UIView

时间:2018-11-01 10:31:57

标签: ios swift uiview constraints

我目前正在尝试在Swift中实现微光效果。为此,我创建了一个灰色的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

有没有更简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分: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
}