Swift以编程方式创建和居中图像视图
我有一个图像(图标)数组,我想创建并将它们水平放置在X的中心 以下是一个例子:Swift以编程方式创建和居中图像视图,swift,layout,imageview,constraints,Swift,Layout,Imageview,Constraints,我有一个图像(图标)数组,我想创建并将它们水平放置在X的中心 以下是一个例子: for uniquePlatform in uniquePlatforms { if uniquePlatform == "Platform1" { let platformImage = UIImage(named: "icPlatform1") let platformImageView = PlatformImageView(image:
for uniquePlatform in uniquePlatforms {
if uniquePlatform == "Platform1" {
let platformImage = UIImage(named: "icPlatform1")
let platformImageView = PlatformImageView(image: platformImage)
platformImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(platformImageView)
platformImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 11).isActive = true
platformImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: CGFloat(???)).isActive = true
platformImageView.widthAnchor.constraint(equalToConstant: platformImage!.size.width).isActive = true
platformImageView.heightAnchor.constraint(equalToConstant: platformImage!.size.height).isActive = true
}
if uniquePlatform == "Platform2" {
let platformImage = UIImage(named: "icPlatform2")
let platformImageView = PlatformImageView(image: platformImage)
platformImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(platformImageView)
platformImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 11).isActive = true
platformImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: CGFloat(???)).isActive = true
platformImageView.widthAnchor.constraint(equalToConstant: platformImage!.size.width).isActive = true
platformImageView.heightAnchor.constraint(equalToConstant: platformImage!.size.height).isActive = true
}
我想要的是:如果platforms count==1,那么只需要一个居中的图标。如果>1,则它们都应居中,并且它们之间的间距应为12。每个图标也有不同的宽度/高度考虑将图像视图添加到封装堆栈视图(
UIStackView
),该视图应提供您所需的行为。这正是我想要的。谢谢非常好,很高兴听到堆栈视图适合您!