So I need some custom views that will contain a few elements. I want to be able to set all the views up programatically to get used to not using interface builder.
I've added the image but can't get the label to appear over the UIImageview. I've played around with the code a bit but can't seem to get this to work. Im sure it must be something silly I've missed but can figure it out. Below is the code for the custom view. Both the image and the label text are added for each custom view in the view controller file.
import UIKit
class IntroButton: UIView {
let mainImage = UIImageView()
let titalBackground = UIView()
let mainTital = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(mainTital)
addSubview(mainImage)
addSubview(titalBackground)
setUpTital()
setUpImage()
setUpButton()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addSubview(mainTital)
addSubview(mainImage)
addSubview(titalBackground)
setUpTital()
setUpButton()
setUpImage()
}
func setUpButton() {
//basic view setup
layer.cornerRadius = 20
layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
layer.shadowRadius = 20
layer.shadowOpacity = 100
layer.shadowOffset = CGSize(width: 10, height: 10)
layer.masksToBounds = true
}
//helps with adding image and content to view
override var intrinsicContentSize: CGSize{
return CGSize(width: 200, height: 300)
}
func setUpImage() {
//adding image to the main view and image constraints
mainImage.contentMode = .scaleAspectFill
mainImage.translatesAutoresizingMaskIntoConstraints = false
mainImage.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
mainImage.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
mainImage.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
mainImage.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
mainImage.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
mainImage.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
}
func setUpTital() {
mainTital.font = UIFont(name: "Futura", size: 25)
mainTital.textColor = .white
mainTital.translatesAutoresizingMaskIntoConstraints = false
mainTital.heightAnchor.constraint(equalToConstant: 100).isActive = true
mainTital.widthAnchor.constraint(equalToConstant: self.frame.width).isActive = true
mainTital.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
mainTital.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
mainTital.textAlignment = .left
mainTital.clipsToBounds = true
}
}
You add the label at most back change order to
addSubview(mainImage)
addSubview(titalBackground)
addSubview(mainTital) /// last 1 appears at most top