Answers:
该答案是对Swift 3的更新。
这是您可以通过编程方式添加图像视图以控制约束的方式。
Class ViewController: UIViewController {
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(someImageView) //This add it the view controller without constraints
someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
}
// do not forget the `.isActive = true` after every constraint
func someImageViewConstraints() {
someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
}
您可以在一行中使用以上内容。
let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)
在Swift 3.0中:
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300));
imageView.image = UIImage(named:"Test.jpeg")
self.view.addSubview(imageView)
let imageView = UIImageView(named: "Test.jpeg"); self.view.addSubview(imageView)
。2行,您使用常量而不是变量。然后使用自动约束放置它。
谢谢,曼恩纳巴赫(MEnnabah),只需将您=
在声明语句中缺少符号的位置添加到代码中:
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
}()
其他一切都对Swift 3来说都是完美的。
在Swift 4.2和Xcode 10.1中
//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view
//Add image view properties like this(This is one of the way to add properties).
extension UIImageView {
//If you want only round corners
func imgViewCorners() {
layer.cornerRadius = 10
layer.borderWidth = 1.0
layer.masksToBounds = true
}
}
斯威夫特4:
首先为您的UIImageView创建一个插座
@IBOutlet var infoImage: UIImageView!
然后在UIImageView中使用image属性
infoImage.image = UIImage(named: "icons8-info-white")
UIImage(named:...)
。正如文档所说:“如果您有一个仅显示一次的图像文件,并希望确保不会将其添加到系统的缓存中,则应改用创建图像UIImage(contentsOfFile:...)
。这样可以避免一次性图像系统映像缓存,可以改善应用程序的内存使用特征。” 仅供参考。