こんばんわ
画像表示ついて質問がございます。
「contentView.contentMode = .scaleAspectFill」を設定しているのですが、
反映されず困っています。。。
コードをご覧頂いて誤りがないかご確認いただくことはできないでしょうか。
*ストーリーボードには何も記載していません。
・コード
override func viewDidLoad() { super.viewDidLoad() //image let imageurl = NSURL(string: "(*画像URL記載)") let imageData = try? NSData(contentsOf: imageurl! as URL,options: NSData.ReadingOptions.mappedIfSafe) let contentimage = UIImage(data:imageData! as Data) let imageView = UIImageView(image:contentimage) ** contentView.contentMode = .scaleAspectFill contentView.clipsToBounds = true** self.contentView.addSubview(imageView) } }
■解決済み
下記方法にて解決いたしました。皆様ご回答ありがとうございました。
コード修正①
override func viewDidLoad() { super.viewDidLoad() //image let imageurl = NSURL(string: "(*画像URL記載)") let imageData = try? NSData(contentsOf: imageurl! as URL,options: NSData.ReadingOptions.mappedIfSafe) let contentimage = UIImage(data:imageData! as Data) let imageView = UIImageView(image:contentimage) //修正 imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true self.contentView.addSubview(imageView) //追記 contentView.addFitConstraints(to: imageView) }
コード追記
extension UIView { func addFitConstraints(to: UIView) { to.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: to, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: to, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: to, attribute: .bottom, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: to, attribute: .trailing, multiplier: 1.0, constant: 0)) } }
回答2件
あなたの回答
tips
プレビュー