如何将 Facebook 闪烁添加到图像和 UIView 中?

How do you add Facebook shimmering to images and UIViews?

我正在试用 Facebook 微光库,我能够使用此代码向文本标签添加微光。

    self.shimmeringView = FBShimmeringView(frame: CGRectMake(0, 0, 200, (self.navigationController?.navigationBar.bounds.height)!))
    self.shimmeringView.contentView = navLabel
    self.navigationItem.titleView = self.shimmeringView
    self.shimmeringView.shimmering = true

但是,我无法使图像或 UIImage 闪光。这可能吗?谢谢!

你让 UIImageView 闪烁的做法是错误的。

  1. 您没有将 shimmer 作为子视图添加到视图中。
  2. 您没有将 UIImageView 设置为微光的 contentView

用类似的东西更新你的代码:

@IBOutlet var imageView: UIImageView!

var shimmer: FBShimmeringView!

override func viewDidLoad() {
    shimmer = FBShimmeringView(frame: self.imageView.frame)
    shimmer.contentView = imageView
    self.view.addSubview(shimmer)
    shimmer.isShimmering = true
}

我对@Shubhank 的回答有疑问,尽管大部分答案都很好。

使用 viewDidLoad 而不是 viewDidLayoutSubviews 作为 shimmer frame 并没有给我想要的结果。

所以我更新了代码,一切正常。

@IBOutlet var imageView: UIImageView!

var shimmer: FBShimmeringView!

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        shimmer = FBShimmeringView(frame: self.imageView.frame)
        shimmer.contentView = imageView
        self.view.addSubView(shimmer)
        shimmer.shimmering = true
}

Swift 3 微光 (1.0.2):

var imageView: UIImageView!

var shimmer: FBShimmeringView!

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    shimmer = FBShimmeringView(frame: self.imageView.frame)
    shimmer.contentView = imageView
    self.view.addSubview(shimmer)
    shimmer.isShimmering = true
}

您也可以使用约束,而无需在每次视图布局子视图时都初始化 shimmer 视图:

let shimmer = FBShimmeringView(frame: .zero)
view.addSubview(shimmer)
shimmer.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: shimmer, attribute: .leading, relatedBy: .equal, toItem: navLabel, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: shimmer, attribute: .trailing, relatedBy: .equal, toItem: navLabel, attribute: .trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: shimmer, attribute: .top, relatedBy: .equal, toItem: navLabel, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: shimmer, attribute: .bottom, relatedBy: .equal, toItem: navLabel, attribute: .bottom, multiplier: 1, constant: 0)
view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])