ios - Swift- 将图像宽度设置为等于外部图像的宽度

标签 ios swift xcode image imageview

我正在使用 NewsAPI 获取新闻,并在 ImageView 显示当前新闻图像的地方使用它。我希望能够将 ImageView 的宽度设置为等于图像的宽度,但图像不断变化,因为它是实时新闻提要。有谁知道我将如何做到这一点?

最佳答案

这就是我想出来的:

假设您希望模糊效果在标签尺寸改变时改变。 (模糊效果是label的supper view)

    view.addSubview(progressTextVisualEffectView)
    NSLayoutConstraint.activate([
        progressTextVisualEffectView.topAnchor.constraint(equalTo: iosImage.topAnchor, constant: 20),
        progressTextVisualEffectView.leftAnchor.constraint(equalTo: iosImage.leftAnchor, constant: 20),
        progressTextVisualEffectView.heightAnchor.constraint(equalToConstant: 36),
        ])
    progressTextVisualEffectView.autoresizesSubviews = true

    progressTextVisualEffectView.contentView.addSubview(progressLabel)
    NSLayoutConstraint.activate([
        progressLabel.centerXAnchor.constraint(equalTo: progressTextVisualEffectView.centerXAnchor),
        progressLabel.centerYAnchor.constraint(equalTo: progressTextVisualEffectView.centerYAnchor),
        progressLabel.rightAnchor.constraint(equalTo: progressTextVisualEffectView.rightAnchor, constant: -10),
        progressLabel.leftAnchor.constraint(equalTo: progressTextVisualEffectView.leftAnchor, constant: 10)
        ])

}

let progressLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "1 / 111112"
    label.textColor = UIColor(white: 1, alpha: 0.7)
    label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
    label.sizeToFit()
    return label
}()

let progressTextVisualEffectView: UIVisualEffectView = {
    let blurEffect = UIBlurEffect(style: .dark)
    let blur = UIVisualEffectView(effect: blurEffect)
    blur.layer.cornerRadius = 12
    blur.clipsToBounds = true
    blur.translatesAutoresizingMaskIntoConstraints = false
    blur.sizeToFit()
    return blur
}()

最重要的是

progressTextVisualEffectView.autoresizesSubviews = true

这是我第一次回答这个问题,所以如果你仍然不知道该怎么做,可以问我。

关于ios - Swift- 将图像宽度设置为等于外部图像的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837359/

相关文章:

ios - 子类化 UILabel 无法按预期工作

c++ - 在Mac OS X Lion(10.8.2)上使用Xcode 4.6安装OpenCV。

ios - Xcode 和 Swift。宽度是自动计算的,但在 iPhone Xr 上一切正常,在 iPhone X 上看起来很糟糕

iOS Facebook SDK 批量请求,单个完成 block

ios - 在 View 变换(旋转)和调整大小(到边界)后保持自动布局

ios - 如何将 sysex 数据添加到 MusicTrack? (音频工具箱)

ios - Swift - 在编辑模式下更改表格单元格背景

xcode - iPAD GUI开发的最佳实践是什么

iOS 沙盒测试与生产

ios - 错误产生转换为 swift 3.0