首页 > 解决方案 > 尝试为 iOS 编程锚定图像

问题描述

这是我的代码

import UIKit

class PageCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupViews()
    }

    let imageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.backgroundColor = .yellow
        iv.image = UIImage(named: "page1")
        return iv
    }()

    func setupViews() {
        backgroundColor = .blue

        addSubview(imageView)
        imageView.(topAnchor, bottomAnchor, rightAnchor, leftAnchor)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

编译时显示此错误。Value of type 'UIImageView' has no member 'anchorToTop'顺便说一句,我试图将图像锚定到单个 UIImageViewCell。

标签: iosuser-interfaceanchor

解决方案


你可以试试

func setupViews() {

     backgroundColor = .blue
     imageView.translatesAutoresizingMaskIntoConstraints = false
     self.contentView.addSubview(imageView)
     imageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0 ).isActive = true
     imageView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0 ).isActive = true
     imageView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 0 ).isActive = true
     imageView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: 0 ).isActive = true
 }

推荐阅读