How to place an ImageView in the center of a UIView? Code:
let dailyUIView = UIView(frame: CGRect(x: 0, y: 420, width: view.frame.size.width, height: 40))
dailyUIView.layer.masksToBounds = true
dailyUIView.backgroundColor = UIColor(named: "dailyTest")
scrollView.addSubview(dailyUIView)
let weatherIconImageView = UIImageView(frame: CGRect(x: 70, y: 0, width: 60, height: 60))
weatherIconImageView.image = UIImage(named: "01d")
dailyUIView.addSubview(weatherIconImageView)
CodePudding user response:
let dailyUIView = UIView(frame: CGRect(x: 0, y: 420, width: view.frame.size.width, height: 40))
dailyUIView.layer.masksToBounds = true
dailyUIView.backgroundColor = UIColor(named: "dailyTest")
scrollView.addSubview(dailyUIView)
let weatherIconImageView = UIImageView(frame: CGRect(x: 70, y: 0, width: 60, height: 60))
weatherIconImageView.image = UIImage(named: "01d")
dailyUIView.addSubview(weatherIconImageView)
weatherIconImageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
weatherIconImageView.widthAnchor.constraint(equalToConstant: 60),
weatherIconImageView.heightAnchor.constraint(equalToConstant: 60),
weatherIconImageView.centerXAnchor.constraint(equalTo: dailyUIView.centerXAnchor),
weatherIconImageView.centerYAnchor.constraint(equalTo: dailyUIView.centerYAnchor),
])
CodePudding user response:
try this it will maybe help
let dailyUIView = UIView(frame: CGRect(x: 0, y: 420, width: view.frame.size.width, height: 40))
dailyUIView.layer.masksToBounds = true
dailyUIView.backgroundColor = UIColor(named: "dailyTest")
scrollView.addSubview(dailyUIView)
let weatherIconImageView = UIImageView(frame: CGRect(x: 70, y: 0, width: 60, height: 60))
weatherIconImageView.image = UIImage(named: "01d")
dailyUIView.addSubview(weatherIconImageView)
weatherIconImageView.translatesAutoresizingMaskIntoConstraints = false
weatherIconImageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
weatherIconImageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
weatherIconImageView.centerXAnchor.constraint(equalTo: dailyUIView.centerXAnchor).isActive = true
weatherIconImageView.centerYAnchor.constraint(equalTo: dailyUIView.centerYAnchor).isActive = true