Autolayout constraints set in code not appearing in interface builder - swift

I have a custom view that is set in interface builder with top, leading, trailing, height constraints.
In my Custom view i have a title and a button.
Im trying to add to the title a bottom and centerY constraints.
and to the button width, height, bottom, leading constraints.
When i add any constraint i get an warning in interface builder:
Expected: width=600, height=68.
Actual: width=0, height=0
When i run the code everything works, but i cant see anything in interface builder.
code:
#IBDesignable
class UIHeader: UIView {
var delegate: HeaderDelegate?
private lazy var titleLable: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = UIFont(name: "Lato-Light", size: 16)
lbl.text = "Title"
return lbl
}()
private lazy var backButton: UIButton = {
let btn = UIButton()
btn.tintColor = UIColor.lightGrayColor()
btn.translatesAutoresizingMaskIntoConstraints = false
let image = UIImage(named: "prev")
if let image = image {
btn.setImage(image.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
}
btn.addTarget(self, action: #selector(UIHeader.OnBackButtonClickLister(_:)), forControlEvents: .TouchUpInside)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
extension UIHeader {
#IBInspectable
var backButtonImage: UIImage? {
get {
return backButton.imageForState(.Normal)
}
set (newImage) {
backButton.setImage(newImage?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
}
}
#IBInspectable
var title: String? {
get {
return titleLable.text
}
set (newTitle) {
titleLable.text = newTitle
}
}
}
extension UIHeader {
private func setupView() {
backgroundColor = UIColor.whiteColor()
translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLable)
addSubview(backButton)
//add shadow
layer.shadowColor = UIColor(white: 115/255, alpha: 1.0).CGColor
layer.shadowOpacity = 0.5
layer.shadowRadius = 8
layer.shadowOffset = CGSizeMake(0, -1)
NSLayoutConstraint.activateConstraints([
//Title//
//center x
NSLayoutConstraint(item: titleLable, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0),
//bottom
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: titleLable, attribute: .Bottom, multiplier: 1, constant: 12),
//button//
//bottom
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: backButton, attribute: .Bottom, multiplier: 1, constant: 4),
//leading
NSLayoutConstraint(item: backButton, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0),
//width
NSLayoutConstraint(item: backButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: 40),
//height
NSLayoutConstraint(item: backButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 40)
])
}
}
I also tried to add the constraints with:
addConstraint(NSLayoutConstraint)
cant figure out what is the problem.
Thanks

I removed
translatesAutoresizingMaskIntoConstraints = false
and everything works great.

Related

Programatically Created Label Within Container View Won't Expand For Text

I have a reusable view class, with the function .addDisapearingView() when added to another view displays the text in the functions parameters. Both the label and its container view are programmatically created. When there's long text in the label, I want the label, and the view to both grow in height. When there's text too long for the label, the label doesn't grow-and the text, subsequently, doesn't clip/go to next line. I'm trying to get the container view to expand programmatically based upon the text.
I've tried an extension that detects when the label is truncated. Using that extension, I used the += operator on the label and view to expand both of them with no luck.
while label.isTruncated {
print("printing while truncating in the while loop")
regView.frame.size.height += 5
label.frame.size.height += 5
}
The interesting thing with that is, I've used that code before, with the addition of adding 5 to the height constraint of the view in the storyboard to expand the size of the label for text, and it worked. That lead me to believe that my problem might reside somewhere in editing the height constraint for the regView.
I've tried countless variations of
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 3
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
label.frame.size.height = regView.frame.size.height
label.sizeToFit()
regView.layoutSubviews()
I've tried changing the frame of the view and label, changing the constaints at the top of the code, and the answers from other questions.
Code:
Truncated Label Extension:
extension UILabel {
var isTruncated: Bool {
guard let labelText = text else {
return false
}
let labelTextSize = (labelText as NSString).boundingRect(
with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: font],
context: nil).size
return labelTextSize.height > bounds.size.height
}
}
View constraint changer:
extension UIView {
func updateConstraint(attribute: NSLayoutAttribute, constant: CGFloat) -> Void {
if let constraint = (self.constraints.filter{$0.firstAttribute == attribute}.first) {
constraint.constant = constant
self.layoutIfNeeded()
}
}
}
Whole function:
func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){
regView.backgroundColor = colorView
regView.alpha = alpha
regView.frame = CGRect(x: toview.bounds.minX, y: toview.bounds.minY, width: toview.frame.size.width, height: height)
toview.addSubview(regView)
regView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = toview.safeAreaLayoutGuide
regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
regView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
regView.heightAnchor.constraint(equalToConstant: height).isActive = true
} else {
NSLayoutConstraint(item: regView,
attribute: .top,
relatedBy: .equal,
toItem: toview, attribute: .top,
multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: regView,
attribute: .leading,
relatedBy: .equal, toItem: toview,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: regView, attribute: .trailing,
relatedBy: .equal,
toItem: toview,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: regView, attribute: NSLayoutAttribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
//regView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
let label = UILabel(frame: CGRect(x: regView.frame.origin.x, y: regView.frame.origin.y, width: regView.frame.width, height: height))
label.text = text
label.font = UIFont(name: "Arial", size: 12)
label.textColor = textColor
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 3
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
label.frame.size.height = regView.frame.size.height
label.sizeToFit()
regView.layoutSubviews()
regView.addSubview(label)
print("Label Height: \(label.frame.height)")
print("Reg view height: \(regView.frame.height)")
while label.isTruncated {
print("label is truncated")
regView.frame.size.height += 5
label.frame.size.height += 5
label.updateConstraint(attribute: NSLayoutAttribute.height, constant: regView.frame.height)
label.updateConstraint(attribute: NSLayoutAttribute.width, constant: regView.frame.width)
regView.layoutSubviews()
label.sizeToFit()
print("Label Height: \(label.frame.height)")
print("Reg view height: \(regView.frame.height)")
}
//remove
Timer.scheduledTimer(withTimeInterval: 2.8, repeats: false) { (action) in
UIView.animate(withDuration: 2.8, animations: {
self.regView.removeFromSuperview()
label.removeFromSuperview()
})
}
}
which is called by: ReusableView().addDisapearingView(toview: self.view, text: "Anonymous posts will still show up in your profile page!, more text text to test in teh view that doen't work!", textColor: UIColor.white, colorView: UIColor.darkGray, alpha: 0.9, height: 20)
The interesting thing(That I tried to fix) was that even if the height is set to 40, or a value where two lines of text could fit, the label still doesn't expand/truncate, much less if the height param is 20.
Any help would be greatly appreciated!
I guess you completely need auto-layout and make regView expand according to the label's text without any height constraints
let regView = UIView()
func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){
regView.backgroundColor = colorView
regView.alpha = alpha
toview.addSubview(regView)
regView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = toview.safeAreaLayoutGuide
NSLayoutConstraint.activate([
regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
regView.topAnchor.constraint(equalTo: guide.topAnchor),
// regView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
// regView.heightAnchor.constraint(equalToConstant: height).isActive = true
])
} else {
NSLayoutConstraint(item: regView,
attribute: .top,
relatedBy: .equal,
toItem: toview, attribute: .top,
multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: regView,
attribute: .leading,
relatedBy: .equal, toItem: toview,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: regView, attribute: .trailing,
relatedBy: .equal,
toItem: toview,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
// NSLayoutConstraint(item: regView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
//regView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
let label = UILabel()
label.text = text
label.font = UIFont(name: "Arial", size: 12)
label.textColor = textColor
label.numberOfLines = 3
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
regView.addSubview(label)
NSLayoutConstraint.activate([
label.trailingAnchor.constraint(equalTo: regView.trailingAnchor),
label.leadingAnchor.constraint(equalTo: regView.leadingAnchor),
label.topAnchor.constraint(equalTo: regView.topAnchor),
label.bottomAnchor.constraint(equalTo: regView.bottomAnchor) // this is the key behind expanding
])
Timer.scheduledTimer(withTimeInterval:3, repeats: false) { (action) in
UIView.animate(withDuration: 2.8, animations: {
self.regView.removeFromSuperview()
})
}
}
Edit:
let regView = UIView()
func addDisapearingView(toview: UIView, text: String, textColor: UIColor, colorView: UIColor, alpha: CGFloat, height: CGFloat){
regView.backgroundColor = colorView
regView.alpha = alpha
toview.addSubview(regView)
regView.translatesAutoresizingMaskIntoConstraints = false
var topCon:NSLayoutConstraint!
if #available(iOS 11.0, *) {
let guide = toview.safeAreaLayoutGuide
topCon = regView.bottomAnchor.constraint(equalTo: guide.topAnchor)
topCon.isActive = true
NSLayoutConstraint.activate([
regView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
regView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
// regView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
// regView.heightAnchor.constraint(equalToConstant: height).isActive = true
])
} else {
topCon = NSLayoutConstraint(item: regView,
attribute: .bottom,
relatedBy: .equal,
toItem: toview, attribute: .top,
multiplier: 1.0, constant: 0)
topCon.isActive = true
NSLayoutConstraint(item: regView,
attribute: .leading,
relatedBy: .equal, toItem: toview,
attribute: .leading,
multiplier: 1.0,
constant: 0).isActive = true
NSLayoutConstraint(item: regView, attribute: .trailing,
relatedBy: .equal,
toItem: toview,
attribute: .trailing,
multiplier: 1.0,
constant: 0).isActive = true
// NSLayoutConstraint(item: regView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: .equal, toItem: toview, attribute: .height, multiplier: 1.0, constant: height).isActive = true
//regView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
let label = UILabel()
label.text = text
label.font = UIFont(name: "Arial", size: 12)
label.textColor = textColor
label.numberOfLines = 3
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
regView.addSubview(label)
NSLayoutConstraint.activate([
label.trailingAnchor.constraint(equalTo: regView.trailingAnchor),
label.leadingAnchor.constraint(equalTo: regView.leadingAnchor),
label.topAnchor.constraint(equalTo: regView.topAnchor),
label.bottomAnchor.constraint(equalTo: regView.bottomAnchor) // this is the key behind expanding
])
regView.layoutIfNeeded()
topCon.constant += self.regView.frame.height
UIView.animate(withDuration: 2) {
toview.layoutIfNeeded()
}
Timer.scheduledTimer(withTimeInterval:3, repeats: false) { (action) in
UIView.animate(withDuration: 2.8, animations: {
self.regView.removeFromSuperview()
})
}
}

UICollectionViewFlowLayout issues with collectionview and textfields

I have an app that uses a collectionview that scrolls horizontally, and has collectionviewcells inside of it. Everything was going fine until I tried to implement a login/register cell with 2 textfields in it using textfielddelegate. When I press on one of the textfields, the keyboard shows for a split second and then hides. After it does this, the view is pushed down a little bit and if I press the textfield again, it is pushed up and wont come down. Here are some screenshots of what it looks like:
before touching a textfield vs. after I touch a textfield
I get various UICollectionViewFlowLayout errors that call for me to make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes.
The behavior of the UICollectionViewFlowLayout is not defined because:
2017-04-26 13:55:03.199199-0400 Eyetube[1500:243622] 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.
2017-04-26 13:55:03.200490-0400 Eyetube[1500:243622] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x10453ee90>, and it is attached to <UICollectionView: 0x104806800; frame = (0 0; 768 960); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x17405a610>; layer = <CALayer: 0x17002f0a0>; contentOffset: {2304, 0}; contentSize: {3072, 910}> collection view layout: <UICollectionViewFlowLayout: 0x10453ee90>.
2017-04-26 13:55:03.200575-0400 Eyetube[1500:243622] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
I tried debugging this multiple times, but it isn't too helpful in finding where exactly the error is coming from. I've been stuck on this issue for hours and can't seem to figure it out.
Where I initialize my layout in my collectionviewcontroller:
func setupCollectionView() {
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
}
collectionView?.backgroundColor = UIColor.white
collectionView?.register(VideoFeedCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(ChannelFeedCell.self, forCellWithReuseIdentifier: channelCellId)
collectionView?.register(ARFeedCell.self, forCellWithReuseIdentifier: augmentedRealityCellId)
collectionView?.register(LoginRegisterCell.self, forCellWithReuseIdentifier: loginRegisterCellId)
collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 50, 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 50, 0)
collectionView?.isPagingEnabled = true
}
My sizeForItemAt func, also in my collectionviewcontroller (P.S., I am subtracting 50 from the height because of the bottom menubar I have added as a subview of the view. I also changed the collectionview's contentInset and scrollIndicatorInsets because of this):
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = CGSize(width: view.frame.width, height: view.frame.height - 50)
return cellSize
}
Here is the complete code of the collectionviewcell, where I am having the issues:
import UIKit
class LoginRegisterCell: BaseCell, UITextFieldDelegate {
let logoImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "eyetube_logo_font")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
let emailTextField: LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.keyboardType = .emailAddress
tf.placeholder = "Enter email"
tf.substituteFontName = "SourceSansPro-Regular"
tf.layer.borderColor = UIColor.rgb(220, green: 220, blue: 220).cgColor
tf.layer.borderWidth = 1
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let passwordTextField: LeftPaddedTextField = {
let tf = LeftPaddedTextField()
tf.placeholder = "Enter password"
tf.substituteFontName = "SourceSansPro-Regular"
tf.layer.borderColor = UIColor.rgb(220, green: 220, blue: 220).cgColor
tf.layer.borderWidth = 1
tf.isSecureTextEntry = true
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
lazy var loginButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.rgb(225, green: 31, blue: 40)
button.titleLabel?.font = UIFont(name: "SourceSansPro-SemiBold", size: 20)
button.setTitle("Log In", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
return button
}()
lazy var registerLink: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Don't have an account? Register here", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont(name: "SourceSansPro-Regular", size: 18)
button.setTitleColor(UIColor.darkGray, for: .normal)
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: (button.titleLabel?.text)!, attributes: underlineAttribute)
button.titleLabel?.attributedText = underlineAttributedString
button.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
return button
}()
var containerView: UIView!
override func setupViews() {
super.setupViews()
self.emailTextField.delegate = self
emailTextField.returnKeyType = .next
self.passwordTextField.delegate = self
passwordTextField.returnKeyType = .done
containerView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
containerView.backgroundColor = .green
addSubview(containerView)
containerView.addSubview(logoImageView)
containerView.addSubview(emailTextField)
containerView.addSubview(passwordTextField)
containerView.addSubview(loginButton)
containerView.addSubview(registerLink)
setupLogoImageView()
setupInputs()
setupLoginButton()
setupRegisterLink()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func handleLogin() {
//first check if the email/password textfields are empty or not
guard let email = emailTextField.text , !email.isEmpty else {
let alert = UIAlertView (title: "Invalid Email", message: "Please enter an email to log in", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
guard let password = passwordTextField.text , !password.isEmpty else {
let alert = UIAlertView (title: "Invalid Password", message: "Please enter a password to log in", delegate: self, cancelButtonTitle: "OK")
alert.show()
return
}
//create session here
ApiLoginAuthentication.sharedInstance.login_now(username: email, password: password, onCompletion: {(loginSuccessful: Bool) -> Void in
guard (loginSuccessful) else {
DispatchQueue.main.async {
let alert = UIAlertView (title: "Invalid Account info", message: "The account information entered is invalid. Please log in with a valid account.", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
return
}
DispatchQueue.main.async {
self.emailTextField.text = ""
self.passwordTextField.text = ""
}
print("the login was successful")
})
/**
let profileUrl: String = "https://eyetube.net/user/profile.asp"
ApiLoginAuthentication.sharedInstance.getContent(contentUrl: profileUrl, onCompletion: {(responseString: String, isLoggedIn: Bool) -> Void in
print(responseString)
print("user status: \(isLoggedIn)")
let json: Any?
do {
let data: NSData = responseString.data(using: String.Encoding.utf8)! as NSData
json = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
print(json)
} catch let error {
print("error: \(error)")
}
})**/
}
func handleRegister() {
let eyetubeRegisterLink = "https://eyetube.net/user/register.asp?rUrl="
UIApplication.shared.openURL(URL(string: eyetubeRegisterLink)!)
}
func setupLogoImageView() {
var sizeConstant: CGFloat!
var centerYConstant: CGFloat!
if UI_USER_INTERFACE_IDIOM() == .pad {
sizeConstant = 400
centerYConstant = -260
} else {
sizeConstant = 200
centerYConstant = -160
}
NSLayoutConstraint(item: logoImageView, attribute: .centerY, relatedBy: .equal, toItem: containerView, attribute: .centerY, multiplier: 1, constant: centerYConstant!).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: sizeConstant).isActive = true
NSLayoutConstraint(item: logoImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: sizeConstant).isActive = true
}
func setupInputs() {
var widthConstant: CGFloat!
var leftConstant: CGFloat!
if UI_USER_INTERFACE_IDIOM() == .pad {
widthConstant = -64
leftConstant = 32
} else {
widthConstant = -32
leftConstant = 16
}
NSLayoutConstraint(item: emailTextField, attribute: .top, relatedBy: .equal, toItem: logoImageView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1, constant: leftConstant).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 1, constant: widthConstant).isActive = true
NSLayoutConstraint(item: emailTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .top, relatedBy: .equal, toItem: emailTextField, attribute: .bottom, multiplier: 1, constant: 8).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1, constant: leftConstant).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 1, constant: widthConstant).isActive = true
NSLayoutConstraint(item: passwordTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
}
func setupLoginButton() {
NSLayoutConstraint(item: loginButton, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: passwordTextField, attribute: .bottom, multiplier: 1, constant: 16).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .width, relatedBy: .equal, toItem: passwordTextField, attribute: .width, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 50).isActive = true
}
func setupRegisterLink() {
NSLayoutConstraint(item: registerLink, attribute: .centerX, relatedBy: .equal, toItem: containerView, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .top, relatedBy: .equal, toItem: loginButton, attribute: .bottom, multiplier: 1, constant: 12).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .width, relatedBy: .equal, toItem: loginButton, attribute: .width, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: registerLink, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 40).isActive = true
}
}

How do I send subviews to front programmatically? (have tried bringSubview to front)

In my UICollectionViewCell I have an image and a label. The picture takes up the whole cell (which I want) - however, the label is placed behind the image, so it's not visible. I have tried bringSubview(toFront: titleLabel), but nothing happens... I got no clue what to do really, have done a lot of searching.
This is the code for the cell, I don't use Storyboard as you can see (sorry for messy constraints, was testing different solutions to find out if this was the problem)
import UIKit
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupBasket()
}
func setupViews() {
}
func setupBasket(){
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class VideoCell: BaseCell {
var selectedItemID : String!
static let sharedInstance = VideoCell()
var video: Video? {
didSet {
titleLabel.text = video?.title
setupThumbnailImage()
}
}
func setupThumbnailImage() {
if let thumbnailImageUrl = video?.thumbnail_image_name {
thumbnailImageView.loadImageUsingUrlString(thumbnailImageUrl)
}
}
let thumbnailImageView: CustomImageView = {
let imageView = CustomImageView()
imageView.image = UIImage(named: "taylor_swift_blank_space")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
let titleLabel: UILabel = {
let textView = UILabel()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "Clothes"
textView.textColor = UIColor.lightGray
return textView
}()
let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
return view
}()
var titleLabelHeightConstraint: NSLayoutConstraint?
let addtoBasket = UIButton(type: .contactAdd)
override func setupViews() {
addtoBasket.frame = CGRect(x: 50, y: 0, width: 20, height: 60)
addSubview(addtoBasket)
addSubview(titleLabel)
addSubview(thumbnailImageView)
addSubview(separatorView)
addSubview(addtoBasket)
titleLabel.superview!.bringSubview(toFront: titleLabel)
//horizontal constraints
addConstraintsWithFormat("H:|-0-[v0]-0-|", views: thumbnailImageView)
//vertical constraints
addConstraintsWithFormat("V:|-1-[v0]-1-|", views: thumbnailImageView)
addConstraintsWithFormat("H:|-0-[v0]-1-|", views: separatorView)
addtoBasket.translatesAutoresizingMaskIntoConstraints = false
addtoBasket.heightAnchor.constraint(equalToConstant: 20).isActive = true
addtoBasket.widthAnchor.constraint(equalToConstant: 20).isActive = true
addtoBasket.centerXAnchor.constraint(equalTo: addtoBasket.superview!.centerXAnchor, constant: 90).isActive = true
addtoBasket.centerYAnchor.constraint(equalTo: addtoBasket.superview!.centerYAnchor, constant: -50).isActive = true
//top constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 8))
//right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0))
//right constraint
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 20))
//height constraint
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: -10)
addConstraint(titleLabelHeightConstraint!)
}
}
Try accessing the labels layer and set its zPosition.
Try titleLabel.layer.zPosition = 1
There was clearly something wrong with the constraints, now working! Thanks

Programmatic Constraints not working as expected

I've spent hours trying to hunt down what is preventing my constraints layout from working. I have a view called ABSegment which simply holds a UILabel which should be centered and have equal height and width as its superview.
I'll include the entire class definition of this UIView subview to show what I've done.
import UIKit
class ABSegment: UIView {
let titleLabel = UILabel()
init(withTitle title: String) {
titleLabel.text = title
titleLabel.textAlignment = .center
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLabel)
backgroundColor = UIColor.blue
}
override func layoutSubviews() {
super.layoutSubviews()
logFrames()
}
func logFrames() {
print("self.frame is \(frame)")
print("titleLabel.frame is \(titleLabel.frame)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
logFrames()
titleLabel.removeConstraints(titleLabel.constraints)
let centerX = NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let centerY = NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerX, centerY, width, height])
super.updateConstraints()
}
}
One natural thing to suspect is that I'm not initializing this view with initWithFrame. Rather, I'm deferring the frame setting until later in the code where these views are constructed. So code that constructs these don't set the frame. The frame may be set in Storyboard or like this:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let frame = CGRect(x: view.bounds.origin.x + 150, y: view.bounds.origin.y + 200, width: 100, height: 100)
segment.frame = frame
segment.layoutSubviews()
}
My understanding is that since I'm calling segment.layoutSubviews(), the ABSegment View should have a change to apply the previously activated constraints with a final frame.
There are so many different settings and things to get right in the correct order with no feedback other than not seeing the Label appear at all.
The main problems I see with your code:
You are adding and removing constraints every time updateConstraints is called. You only need to set up the constraints once when you create your view.
You are setting translatesAutoresizingMaskIntoConstraints = false on ABSegment itself. Don't do this. This tells Auto Layout that you will be specifying the size and location of ABSegment using constraints, and you clearly are using a frame for this purpose.
Here is the refactored code:
class ABSegment: UIView {
let titleLabel = UILabel()
// Computed property to allow title to be changed
var title: String {
set {
titleLabel.text = newValue
}
get {
return titleLabel.text ?? ""
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLabel(title: "")
}
convenience init(title: String) {
self.init(frame: CGRect.zero)
self.title = title
}
// This init is called if your view is
// set up in the Storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLabel(title: "")
}
func setupLabel(title: String) {
titleLabel.text = title
titleLabel.textAlignment = .center
addSubview(titleLabel)
backgroundColor = UIColor.blue
titleLabel.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let centerY = NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerX, centerY, width, height])
}
override func layoutSubviews() {
super.layoutSubviews()
logFrames()
}
func logFrames() {
print("self.frame is \(frame)")
print("titleLabel.frame is \(titleLabel.frame)")
}
override func updateConstraints() {
super.updateConstraints()
logFrames()
}
}
Notes:
I moved all of the setup of the label into a function called setupLabel. This allows it to be called by both initializers.
I added a computed property called title to ABSegment which allows you to change the title at any time with mysegment.title = "new title".
I turned init(withSegment:) into a convenience init. It calls the standard init(frame:) and then sets the title. It is not a common practice to use withProperty so I changed it. You'd create an ABSegment with var segment = ABSegment(title: "some title").
I had required init?(coder aDecoder: NSCoder) call setupLabel so that ABSegment can be used with views added in the Storyboard.
The overrides of layoutSubviews and updateConstraints were left in to log the frames. That is all that they do now.

Adding constraints programatically to custom components

I'm developing custom components in Swift by inheriting the default components. Below there is a piece of my code:
class DirectionButton: UIButton {
var backgroundImage: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
styleComponent()
}
override init(frame: CGRect) {
super.init(frame: frame)
styleComponent()
}
func styleComponent() {
backgroundImage = UIImageView(image: UIImage(named: "seta-proximo"))
backgroundImage.contentMode = .ScaleAspectFit
self.setNeedsLayout()
self.layoutIfNeeded()
self.addSubview(backgroundImage)
let imageConstraints = NSLayoutConstraint(item: self, attribute: .TrailingMargin, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 10)
backgroundImage.addConstraint(imageConstraints)
}
}
The backgroundImage variable needs to be 10 points from the right part of the button, that's why I need the constraints.
After running I got an exception like that: The view hierarchy is not prepared for the constraint.
How can I add constraints correctly?
Reading the documentation, I followed the tip to use layout anchors as #AjayBeniwal suggested. The code I needed was the following (after I add the subview to the button):
backgroundImage.trailingAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.trailingAnchor, constant: -10).active = true
backgroundImage.bottomAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.bottomAnchor).active = true
backgroundImage.centerYAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.centerYAnchor).active = true
This way, the image is vertically centralized to the button an 20 points far from the right edge.
Edited
first do this :
backgroundImage.translatesAutoresizingMaskIntoConstraints = false
Add constraint to self not backgroundImage
You are adding constraint from self to self (incorrect) add from backroundImage to self
Constraints are incomplete. You are adding only one trailing constraint.
Overall solution is this:
func styleComponent() {
// Change clear.png with your own image name.
backgroundImage = UIImageView(image: UIImage(named: "clear.png"))
backgroundImage.contentMode = .ScaleAspectFit
self.addSubview(backgroundImage)
backgroundImage.translatesAutoresizingMaskIntoConstraints = false
let imageConstraints = NSLayoutConstraint(item: backgroundImage, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: -10)
self.addConstraint(imageConstraints)
let topConstraints = NSLayoutConstraint(item: backgroundImage, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 10)
self.addConstraint(topConstraints)
let bottomConstraints = NSLayoutConstraint(item: backgroundImage, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: -10)
self.addConstraint(bottomConstraints)
let leadingConstraints = NSLayoutConstraint(item: backgroundImage, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 10)
self.addConstraint(leadingConstraints)
}
The resultant output is this. You can modifiy the constants values to do according to your own will
In this case, The green is a Button and Red one is background image.
Try this and let me know if you are still getting any warning or complications.
//Give Constrain Outlet to ImageView
func setConstrain()
{
self.imageConstrain.constant = -10
self.topConstraints.constant = 10
self.bottomConstraints.constant = -10
self.leadingConstraints.constant = 10
self.layoutIfNeeded()
}