UIView subviews not appearing - ios

I have a view controller with a UIView. Inside that UIView I add elements like a text label. When I run my code it is not there.
import UIKit
class EventDetailViewController: UIViewController {
//variables that will hold data sent in through previous event controller
var eventImage = ""
var eventName = ""
var eventDescription = ""
var eventStreet = ""
var eventCity = ""
var eventState = ""
var eventZip = 0
var eventDate = ""
//
lazy var currentEventImage : UIImageView = {
let currentEvent = UIImageView()
let imageURL = URL(string: self.eventImage)
currentEvent.af_setImage(withURL: imageURL!)
currentEvent.clipsToBounds = true
currentEvent.translatesAutoresizingMaskIntoConstraints = false
currentEvent.contentMode = .scaleToFill
currentEvent.layer.masksToBounds = true
return currentEvent
}()
//will be responsible for creating the UIView that contains relevant event information
let eventInfoContainerView: UIView = {
let infoContainer = UIView()
infoContainer.backgroundColor = UIColor.white
infoContainer.layer.masksToBounds = true
return infoContainer
}()
lazy var eventNameLabel: UILabel = {
let currentEventName = UILabel()
currentEventName.text = self.eventName
currentEventName.translatesAutoresizingMaskIntoConstraints = false
return currentEventName
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
navigationItem.title = eventName
self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "icons8-Back-64"), style: .plain, target: self, action: #selector(GoBack))
self.navigationItem.leftBarButtonItem = backButton
//Subviews will be added here
view.addSubview(currentEventImage)
view.addSubview(eventInfoContainerView)
eventInfoContainerView.addSubview(eventNameLabel)
//Constraints will be added here
_ = currentEventImage.anchor(view.centerYAnchor, left: nil, bottom: nil, right: nil, topConstant: -305, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: self.view.frame.width, heightConstant: 200)
_ = eventInfoContainerView.anchor(currentEventImage.bottomAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
_ = eventNameLabel.anchor(eventInfoContainerView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 20, leftConstant: 32, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
func GoBack(){
_ = self.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I am kind of lost I viewed a tutorial where they added elements to a UIView in a similar fashion and things appeared. Any insight would be helpful. Tried changing multiple things and nothing really made it appear and I have researched a couple answers I know it is probably something small that my eyes are just looking past but I can't discover it at this point.
This is my custom method for setting constraints
import UIKit
extension UIView {
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
topAnchor.constraint(equalTo: top, constant: topConstant).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant).isActive = true
}
if let left = left {
leftAnchor.constraint(equalTo: left, constant: leftConstant).isActive = true
}
if let right = right {
rightAnchor.constraint(equalTo: right, constant: -rightConstant).isActive = true
}
}
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}

OK - now that we see your .anchor(...) function...
The TOP of your label is set to the BOTTOM of eventInfoContainerView with topConstant: 20 ... which is +20
Change that value to -20 (assuming you want the label along the bottom of the view):
_ = eventNameLabel.anchor(eventInfoContainerView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: -20, leftConstant: 32, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
Assuming your .anchor(...) function / extension is working properly, I think the only thing wrong is that you forgot to set:
infoContainer.translatesAutoresizingMaskIntoConstraints = false
when you initialize your eventInfoContainerView

Related

Swift CollectionViewCell has different frame than its CollectionView

I have a CollectionView which has fills the whole screen, has horizontal scrollDirection and is paging enabled. It is inside of a NavigationController with a hidden navigationBar. The CollectionViewCells have the height of the screen too.
What I would expect to happen:
Each cell fills the whole screen and when I swipe to left/right another cell appears and fills the whole screen.
What actually happens:
The cells are not filling the whole screen. There is a little space (approx. 20 pxl) between the top of the cells and the top border of the screen. Also the bottom of the cell (also approx. 20 pxl) is "under" the bottom border of the screen.
Also i get a warning:
The behavior of the UICollectionViewFlowLayout is not defined because:
the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
So the cells height is correct as it seems, but the y-value is wrong.
What I already tried:
override shouldInvalidateLayoutForBoundsChange to return true.
As you can see here the blue border is the border of the collectionView and the red border is the border of the cell. The blue border is, as I would expect it, but I would expect the red border to be like the blue border.
Here is the code:
class LoginController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, LoginControllerDelegate, UIGestureRecognizerDelegate {
lazy var loginCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.dataSource = self
cv.delegate = self
cv.isPagingEnabled = true
cv.layer.borderWidth = 1.0
cv.layer.borderColor = UIColor.blue.cgColor
return cv
}()
let introCellId = "IntroCellId"
let loginCellId = "LoginCellId"
let pages: [Page] = {
let firstPage = Page(title: String,
message: String,
imageName: String)
let secondPage = Page(title: String,
message: String,
imageName: String)
let thirdPage = Page(title: String,
message: String,
imageName: String)
return [firstPage, secondPage, thirdPage]
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isHidden = true
view.addSubview(loginCollectionView)
registerCells()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pages.count + 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == pages.count {
let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell
loginCell.loginControllerDelegate = self
loginCell.layer.borderColor = UIColor.red.cgColor
loginCell.layer.borderWidth = 2.0
return loginCell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: introCellId, for: indexPath) as! PageCell
let page = pages[indexPath.item]
cell.page = page
cell.layer.borderColor = UIColor.red.cgColor
cell.layer.borderWidth = 2.0
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.loginCollectionView.frame.width, height: self.loginCollectionView.frame.height)
}
}
PageCell:
class PageCell: UICollectionViewCell {
var page: Page? {
didSet {
guard let page = page
else {
return
}
imageView.image = UIImage(named: page.imageName)
let color = UIColor(white: 0.2, alpha: 1)
let attributedText = NSMutableAttributedString(string: page.title, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium), NSAttributedString.Key.foregroundColor: color])
attributedText.append(NSMutableAttributedString(string: "\n\n\(page.message)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium), NSAttributedString.Key.foregroundColor: color]))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let length = attributedText.string.count
attributedText.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: length))
textView.attributedText = attributedText
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.backgroundColor = UIColor(displayP3Red: 139/255, green: 221/255, blue: 116/255, alpha: 1)
iv.clipsToBounds = true
return iv
}()
let textView: UITextView = {
let tv = UITextView()
tv.isEditable = false
tv.contentInset = UIEdgeInsets(top: 24, left: 0, bottom: 0, right: 0)
tv.textColor = UIColor(displayP3Red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
return tv
}()
func setupViews() {
addSubview(imageView)
addSubview(textView)
_ = imageView.anchor(topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: screenWidth, heightConstant: (screenHeight) / 2)
_ = textView.anchor(imageView.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: screenWidth, heightConstant: (screenHeight) / 2)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been impremented")
}
}
LoginCell:
class LoginCell: UICollectionViewCell {
let logoImageView: UIImageView = {
let image = UIImage(named: "logo green")
let imageView = UIImageView(image: image)
return imageView
}()
let emailTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "E-Mail"
textField.layer.borderColor = UIColor.lightGray.cgColor
let border = CALayer()
border.frame = CGRect(x: 0, y: 40, width: UIScreen.main.bounds.width - 64, height: 2.0)
border.backgroundColor = UIColor(displayP3Red: 51/255, green: 51/255, blue: 51/255, alpha: 1).cgColor
textField.layer.addSublayer(border)
textField.keyboardType = .emailAddress
return textField
}()
let emailAlertLabel: UILabel = {
let label = UILabel()
label.text = "E-Mail-Adresse nicht gefunden"
label.textColor = .red
label.isHidden = true
return label
}()
let passwordTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Passwort"
textField.layer.borderColor = UIColor.lightGray.cgColor
let border = CALayer()
border.frame = CGRect(x: 0, y: 40, width: UIScreen.main.bounds.width - 64, height: 2.0)
border.backgroundColor = UIColor(displayP3Red: 51/255, green: 51/255, blue: 51/255, alpha: 1).cgColor
textField.layer.addSublayer(border)
textField.isSecureTextEntry = true
return textField
}()
let passwordAlertLabel: UILabel = {
let label = UILabel()
label.text = "Ungültiges Passwort"
label.textColor = .red
label.isHidden = true
return label
}()
lazy var forgotPasswordButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .white
button.setTitle("Passwort vergessen?", for: .normal)
button.setTitleColor(UIColor(displayP3Red: 139/255, green: 221/255, blue: 116/255, alpha: 1), for: .normal)
button.addTarget(self, action: #selector(handleForgotPassword), for: .touchUpInside)
button.contentHorizontalAlignment = .left
return button
}()
lazy var loginButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(displayP3Red: 139/255, green: 221/255, blue: 116/255, alpha: 1)
button.setTitle("Login", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(checkUserData), for: .touchUpInside)
button.layer.cornerRadius = 25.0
return button
}()
weak var loginControllerDelegate: LoginControllerDelegate?
lazy var stayLoggedInSwitch: UISwitch = {
let loginSwitch = UISwitch(frame: CGRect(x: 150, y: 150, width: 0, height: 0))
loginSwitch.addTarget(self, action: #selector(LoginCell.handleStayLoggedInState(_:)), for: .valueChanged)
loginSwitch.setOn(false, animated: true)
return loginSwitch
}()
let stayLoggedInTextField: UITextField = {
let textField = UITextField()
textField.text = "Angemeldet bleiben"
textField.textColor = UIColor(displayP3Red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
textField.isUserInteractionEnabled = false
return textField
}()
let registerLabel: UILabel = {
let label = UILabel()
label.text = "Sie haben noch keinen Account?"
label.textColor = .lightGray
label.backgroundColor = .white
label.font = label.font.withSize(13)
return label
}()
lazy var registerButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .white
button.setTitle("Registrieren", for: .normal)
button.setTitleColor(UIColor(displayP3Red: 139/255, green: 221/255, blue: 116/255, alpha: 1), for: .normal)
button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
button.contentHorizontalAlignment = .left
button.titleLabel?.font = button.titleLabel?.font.withSize(13)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
addSubview(logoImageView)
addSubview(emailTextField)
addSubview(emailAlertLabel)
addSubview(passwordTextField)
addSubview(passwordAlertLabel)
addSubview(forgotPasswordButton)
addSubview(loginButton)
addSubview(stayLoggedInSwitch)
addSubview(stayLoggedInTextField)
addSubview(registerLabel)
addSubview(registerButton)
_ = logoImageView.anchor(centerYAnchor, left: nil, bottom: nil, right: nil, topConstant: -230, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 160, heightConstant: 160)
logoImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
_ = emailTextField.anchor(logoImageView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 35, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = emailAlertLabel.anchor(emailTextField.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 20)
_ = passwordTextField.anchor(emailAlertLabel.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = passwordAlertLabel.anchor(passwordTextField.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 20)
_ = forgotPasswordButton.anchor(passwordAlertLabel.bottomAnchor, left: leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 32, bottomConstant: 0, rightConstant: 0, widthConstant: 200, heightConstant: 25)
_ = loginButton.anchor(forgotPasswordButton.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 4, leftConstant: 32, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 50)
_ = stayLoggedInSwitch.anchor(loginButton.bottomAnchor, left: leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 32, bottomConstant: 0, rightConstant: 0, widthConstant: 60, heightConstant: 50)
_ = stayLoggedInTextField.anchor(loginButton.bottomAnchor, left: stayLoggedInSwitch.rightAnchor, bottom: nil, right: rightAnchor, topConstant: 16, leftConstant: 0, bottomConstant: 0, rightConstant: 32, widthConstant: 0, heightConstant: 32)
_ = registerLabel.anchor(nil, left: leftAnchor, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 32, bottomConstant: 32, rightConstant: 0, widthConstant: 200, heightConstant: 25)
_ = registerButton.anchor(nil, left: registerLabel.rightAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 32, rightConstant: 32, widthConstant: 0, heightConstant: 25)
emailTextField.addTarget(self, action: #selector(underlineTextFieldColor(sender:)), for: .editingDidBegin)
emailTextField.addTarget(self, action: #selector(underlineTextFieldDark(sender:)), for: .editingDidEnd)
passwordTextField.addTarget(self, action: #selector(underlineTextFieldColor(sender:)), for: .editingDidBegin)
passwordTextField.addTarget(self, action: #selector(underlineTextFieldDark(sender:)), for: .editingDidEnd)
}
#objc func underlineTextFieldDark(sender: UITextField) {
sender.layer.sublayers![0].backgroundColor = UIColor(displayP3Red: 51/255, green: 51/255, blue: 51/255, alpha: 1).cgColor
}
#objc func underlineTextFieldColor(sender: UITextField) {
sender.layer.sublayers![0].backgroundColor = UIColor(displayP3Red: 139/255, green: 221/255, blue: 116/255, alpha: 1).cgColor
}
#objc func handleLogin() {
loginControllerDelegate?.finishLoggingIn()
}
#objc func handleStayLoggedInState(_ sender: UISwitch) {
if (sender.isOn == true) {
UserDefaults.standard.setIsLoggedIn(value: true)
}
else {
UserDefaults.standard.setIsLoggedIn(value: false)
}
}
#objc func handleForgotPassword() {
loginControllerDelegate?.finishLoggingIn()
}
#objc func handleRegister() {
loginControllerDelegate?.finishLoggingIn()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The Anchor method:
extension UIView {
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
}
The collection view automatically set to the whole view. The contents of the collectionView is able to adjust the insects automatically if you do not set any behavior. At this case set automatic adjustment false to get the full-screen view. The top and bottom of the screen have a safe area for adjusting view with the notch.
Try this
collectionView?.contentInsetAdjustmentBehavior = .never
Hope this will fix this issue.

Custom buttons can't be tapped Swift

I have created 5 custom buttons all in code, and they all show up perfectly; however, for some reason, there is no response when tapped like they are inactive. I have added the subviews in my ViewDidLoad and coded the constraints in a separate function that's not important I don't believe to this so let me know if that's needed to better your understanding.
The code:
let backgroundImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
return imageView
}()
let transparentView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black
view.backgroundColor = view.backgroundColor?.withAlphaComponent(0.5)
return view
}()
let button1: UIButton = {
let button = UIButton(type: .custom)
button.addTarget(self, action: #selector(button1Pressed), for: .touchUpInside)
button.setImage(UIImage(named: "button"), for: .normal)
button.isUserInteractionEnabled = true
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
addSubviews()
setupViewConstraints()
}
func addSubviews() {
self.view.addSubview(backgroundImageView)
backgroundImageView.addSubview(transparentView)
transparentView.addSubview(button1)
}
func setupViewConstraints() {
backgroundImageView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
transparentView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
button1.anchor(top: nil, left: nil, bottom: view.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 20, paddingRight: 0, width: 80, height: 80)
button1.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
#objc func button1Pressed() {
print("Button1 pressed")
}
By default, user interaction is disabled in UIImageView instances. And when a superview's user interaction is disabled, its subviews can't receive the user interaction, even if you have set button.isUserInteractionEnabled = true
So add imageView.isUserInteractionEnabled = true in backgroundImageView closure
let backgroundImageView: UIImageView = {
let imageView = UIImageView()
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
return imageView
}()

How to make custom class for auto layouts?

Like we make custom classes for UIButton and other items of UIKit.
Just we define our layouts in that class and further use them as we do in case of other custom class.
If it can not happen, kindly comment that why it can't be done?
The below extension can be used for your requirement
extension UIView {
public func anchor(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
}
public func anchor(centerX: NSLayoutXAxisAnchor? = nil, centerY: NSLayoutYAxisAnchor? = nil, xConstant: CGFloat = 0, yConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) {
self.translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let centerX = centerX {
anchors.append(centerXAnchor.constraint(equalTo: centerX, constant: xConstant))
}
if let centerY = centerY {
anchors.append(centerYAnchor.constraint(equalTo: centerY, constant: yConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
}
}
as
label.anchor(centerX: view.centerXAnchor, centerY: view.centerYAnchor, xConstant: 20, yConstant: 5, widthConstant: screenSize.width, heightConstant: height1)
and
label.anchor(top: nil, left: customCell.leftAnchor, bottom: customCell.bottomAnchor, right: customCell.rightAnchor, topConstant: 0, leftConstant: 22, bottomConstant: 0, rightConstant: 22, widthConstant: width, heightConstant: btnHeigght)

Have autosizing text in a viewcontroller

Can someone tell my why this code does not autosize the text in the descLabel? I tried to set the numberOfLines to 0 and I set a lineBreakMode but this pretty much does nothing to solve my problem. Is this approach not possible in a ViewController or do I do something completely wrong?
class SingleEventViewController: UIViewController {
var thisEvent: Event
var eventDescription: String?
let descLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.text = "Beschreibung"
label.textColor = .black
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
return label
}()
let participateButton: UIButton = {
let button = UIButton()
button.backgroundColor = CalendarSettings.Colors.buttonBG
button.setTitle("Teilnehmen", for: .normal)
button.setTitleColor(CalendarSettings.Colors.darkRed, for: .normal)
return button
}()
//MARK: - Init & View Loading
init(event: Event) {
thisEvent = event
super.init(nibName: nil, bundle: nil)
setupDefaultValues()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
applyDefaultValues()
setupViews()
confBounds()
}
//MARK: - Setup
func setupDefaultValues() {
eventDescription = thisEvent.eventDescription
}
func applyDefaultValues() {
descLabel.text = eventDescription
}
func setupViews() {
view.addSubview(descLabel)
view.addSubview(participateButton)
let tabbarHeight = self.tabBarController?.tabBar.frame.height ?? 0
descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
participateButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: tabbarHeight, paddingRight: 0, width: 0, height: 50)
}
To make it autoresize you must give it a left/leading and right/trailing constraints , or a fixed width
descLabel.anchor(top: titleLabel.bottomAnchor, left: view.leftAnchor, bottom: nil, rightview.rightAnchor, paddingTop: 5, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
If it is the font size you are trying to change so that it fits in the label then try adjustFontSizeToWidth, but if it is the label you wish to resize try sizeToFit().

Swift Cannot Round the Corners of my UIButton

I've looked at almost every stackoverflow solution and for some odd reason my button will not round the corners. Can someone check and see what im doing wrong?
let goToMapsButton = UIButton(type: .custom)
scrollView.addSubview(goToMapsButton)
_ = goToMapsButton.anchor(map.bottomAnchor, left: nil, bottom: seperator.topAnchor, right: self.view.rightAnchor, topConstant: 16, leftConstant: 0, bottomConstant: 16, rightConstant: 16, widthConstant: 50, heightConstant: 50)
goToMapsButton.backgroundColor = .green
goToMapsButton.layer.cornerRadius = 0.5 * goToMapsButton.bounds.size.width
goToMapsButton.clipsToBounds = true
goToMapsButton.layer.masksToBounds = true
Btw, Im doing this all in the viewDidLoad section of the view controller, if that info makes a difference.
Here is the full viewDidLoadClass for reference:` override func viewDidLoad() {
super.viewDidLoad()
let map = MKMapView()
let view1 = UIView()
view1.backgroundColor = .red
let storeAddress = UILabel()
storeAddress.text = "318 Atwood Avenue"
storeAddress.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)
let storeCity = UILabel()
storeCity.text = "Rainy River"
storeCity.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium)
let seperator = UIView()
seperator.backgroundColor = .lightGray
let goToMapsButton = UIButton(type: .custom)
scrollView.addSubview(map)
scrollView.addSubview(view1)
scrollView.addSubview(storeAddress)
scrollView.addSubview(storeCity)
scrollView.addSubview(goToMapsButton)
scrollView.addSubview(seperator)
map.anchorToTop(scrollView.topAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor)
map.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.6).isActive = true
_ = storeAddress.anchor(map.bottomAnchor, left: self.view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 16, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
_ = storeCity.anchor(storeAddress.bottomAnchor, left: self.view.leftAnchor, bottom: nil, right: nil, topConstant: 8, leftConstant: 16, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
_ = goToMapsButton.anchor(map.bottomAnchor, left: nil, bottom: nil, right: self.view.rightAnchor, topConstant: 16, leftConstant: 0, bottomConstant: 16, rightConstant: 16, widthConstant: 50, heightConstant: 50)
goToMapsButton.backgroundColor = .green
print(goToMapsButton.frame.width)
goToMapsButton.layer.cornerRadius = 0.25 * goToMapsButton.frame.width
goToMapsButton.clipsToBounds = true
goToMapsButton.layer.masksToBounds = true
_ = seperator.anchor(storeCity.bottomAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 1)
view1.anchorToTop(map.bottomAnchor, left: self.view.leftAnchor, bottom: scrollView.bottomAnchor, right: self.view.rightAnchor)
view1.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.8).isActive = true
}`
Move this code in viewWillLayoutSubviews:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
goToMapsButton.layer.cornerRadius = 0.25 * goToMapsButton.frame.width
}
Or create your custom class for button with rounded corners:
class RoundedButton: UIButton {
#IBInspectable var cornerRadius: CGFloat = 0
override func layoutSubviews() {
super.layoutSubviews()
clipsToBounds = true
layer.cornerRadius = cornerRadius
}
}
I face the same issue today, I'm using Anchor too. Well it looks like a one line stuff to me, never think it would takes that much of code.
The difficult is that we cannot get the frame.height or width in UIButton property closure because autolayout has not calculate the size at that time. I do a test to apply the purely round corner in viewDidLayoutSubviews.
And this is what it is looks like, although the declaration is separated for those UIButtons. I really don't like this way, I want to put all button declaration code in the same place, like a closure. However I don't find any other way to do it in internet.
let b1 = UIButton()
let b2 = UIButton()
let b3 = UIButton()
let b4 = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
configureLayout()
}
private func configureLayout() {
// disable large title
navigationItem.largeTitleDisplayMode = .never
let topLabel = UILabel()
topLabel.text = "Import your music"
topLabel.font = .systemFont(ofSize: 30, weight: .heavy)
topLabel.numberOfLines = 0
topLabel.textColor = .black
topLabel.textAlignment = .center
let stack = UIStackView()
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.spacing = 40
stack.addArrangedSubview(topLabel)
b1.setTitle("Local drive", for: .normal)
b2.setTitle("Google", for: .normal)
b3.setTitle("OneNote", for: .normal)
b4.setTitle("DropBox", for: .normal)
b1.backgroundColor = .myBlue
b2.backgroundColor = .myGreen
b3.backgroundColor = .systemPink
b4.backgroundColor = .myPuple
b1.tag = 1
b2.tag = 2
b3.tag = 3
b4.tag = 4
[b1, b2, b3, b4].forEach { b in
b.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.gray, for: .highlighted)
stack.addArrangedSubview(b)
b.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
view.addSubview(stack)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: g.centerYAnchor),
stack.widthAnchor.constraint(equalTo: g.widthAnchor, multiplier: 0.75)
])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
[b1, b2, b3, b4].forEach { b in
b.layer.cornerRadius = b1.frame.height / 2
b.layer.cornerCurve = .continuous
}
}
Give your button a frame. like that
goToMapsButton.frame = CGRect(x: xposition, y:yposition, width: widthyouwant, height: heightyouwant)
as currently your size of button is zero 0*0.5 = zero thats why its not applying any radius.
give it frame and it will work...
UIButton might have a background UIImage with rounded corners. It allowes you to set a background UIImage for each UIControlState of your UIButton.
open class UIButton : UIControl, NSCoding {
open func setBackgroundImage(_ image: UIImage?, for state: UIControlState)
}
If your UIButton's size is determined at runtime and the radius is fixed - you can use a resizable image:
open class UIImage : NSObject, NSSecureCoding {
open func resizableImage(withCapInsets capInsets: UIEdgeInsets) -> UIImage
}
On the gif below I use UIImage with size = CGSize(width: 7, height: 7), corner radius = 3 and cap insets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)

Resources