【问题标题】:Swift - Duplicate UIViewSwift - 重复的 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 并设置所有需要设置的变量以在你的子类的初始化程序中实现微光效果?
  • 可能需要一个函数来重用?

标签: ios swift uiview constraints


【解决方案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
}

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2011-01-09
    • 2015-04-09
    • 2017-11-27
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多