Custom View in Cocoa can't draw after setting AutoLayout Constraints - swift

On a MacOS Project.
I'm trying to draw a line under a text field (so that by making the text field transparent I can create a "please fill in the blank" style of view that asks the user to input the data). I created a simple subclass of NSView called lineDrawer just to draw the line, then I tried to add an instance of a lineDrawer as a subview to the view where I let the user enter his name. The line should be drawn right below the transparent text field. The text field is an IBOutlet of the view and already in correct position, and I want the line to have the exact same frame as the text field, so that if I draw a path from the lineDrawer's (minX, minY)to (maxX, minY), the path is exactly below the transparent text field.
I can't make it work because after I set
lineView.translatesAutoresizingMaskIntoConstraints = false
and added my own constraints, the custom view wouldn't draw. I think it has something to do with me not giving the program enough information about where exactly to draw the view, but I can't figure out what's lacking here. BTW, if I don't set the constraints, it would just draw the view at its frame's place. If I set the constraints, nothing shows.
The NickName: NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
greetingLine.font = .labelFont(ofSize: 50)
nameField.font = .labelFont(ofSize: 50)
nameField.isBezeled = false
let lineView = lineDrawer.init()
lineView.setFrameSize(nameField.frame.size)
self.view.addSubview(lineView)
lineView.translatesAutoresizingMaskIntoConstraints = false
let lineConstraintX = NSLayoutConstraint.init(item: lineView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let lineConstraintY = NSLayoutConstraint.init(item: lineView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.3, constant: 0)
self.view.addConstraints([lineConstraintY, lineConstraintX])
}
#IBOutlet weak var nameField: NSTextField!
#IBOutlet weak var greetingLine: NSTextField!
and the lineDrawer: NSView:
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
let context = NSGraphicsContext.current?.cgContext
context!.beginPath()
context!.move(to: CGPoint(x: self.bounds.minX, y: self.bounds.minY))
let endPoint = CGPoint.init(x: self.bounds.maxX, y: self.bounds.minY)
context!.addLine(to: endPoint)
context!.move(to: CGPoint(x: 0, y: 0))
context!.addLine(to: CGPoint(x: 10, y: 10))
let loadedColor = ColorGetter.getCurrentThemeColor()
context!.setStrokeColor(loadedColor.cgColor)
context!.setLineWidth(5)
context!.strokePath()
print("drawing")
}
Thanks very much in advance to anyone who would offer help on this!

Can you, please, add behind your layout constraint the variable isActive and set it to be true. Then ist should work.
So, the code you have:
let lineConstraintX = NSLayoutConstraint.init(item: lineView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let lineConstraintY = NSLayoutConstraint.init(item: lineView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.3, constant: 0)
Must be changed in:
NSLayoutConstraint.init(item: lineView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint.init(item: lineView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.3, constant: 0).isActive = true
Then the auto layout constraint is activated and works. Currently, you did set the auto layout constraint, but you didn't activate it.

Answering my own question:
I added 2 constraints to the custom view's width and height by
NSLayoutConstraint.init(item: lineView, attribute: .width, relatedBy: .equal, toItem: self.nameField, attribute: .width, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint.init(item: lineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100).isActive = true
I think by making
lineView.translatesAutoresizingMaskIntoConstraints = false
I was removing the program's knowledge about both the custom view's position and size, and so I had to re-specify them both manually?
Weird that the program doesn't imply what the size of the custom view should be from its frame's size, which was set.

Related

Constraining Text Field to Button in Swift

I have a button I created in my storyboard, but have a custom UITextField that needs to be implemented in code, I am trying to place the text field so that it's 20 pixels above the button, but I am not getting the desired result for some reason. Am I missing something or is this not how you implement it? here's my implementation and output:
#IBOutlet weak var buyPointsButton: UIButton!
lazy var cardTextField: STPPaymentCardTextField = {
let cardTextField = STPPaymentCardTextField()
return cardTextField
}()
In viewDidLoad
self.view.addSubview(cardTextField)
cardTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
NSLayoutConstraint(item: cardTextField, attribute: .bottom, relatedBy: .equal, toItem: buyPointsButton, attribute: .top, multiplier: 1, constant: 70),
NSLayoutConstraint(item: cardTextField, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buyPointsButton.frame.width),
NSLayoutConstraint(item: cardTextField, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0),
NSLayoutConstraint(item: cardTextField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 28)
])
The main problem is that you are setting the text field's .centerY to the view's .centerY and you're constraining the Bottom of the text field to the Top of the button...
You'll find it much easier to work with constraints if you use the more "modern" syntax, and include comments telling yourself what the constraints are - or at least, should be - doing.
For example:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(cardTextField)
cardTextField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Bottom of text field 20-points above Top of button
cardTextField.bottomAnchor.constraint(equalTo: buyPointsButton.topAnchor, constant: -20.0),
// text field Width equal to button Width
cardTextField.widthAnchor.constraint(equalTo: buyPointsButton.widthAnchor),
// text field centered horizontally to button
cardTextField.centerXAnchor.constraint(equalTo: buyPointsButton.centerXAnchor),
// text field Height equal to 28
cardTextField.heightAnchor.constraint(equalToConstant: 28.0),
])
}

Changing position of UIProgressView?

I added a progress bar to my screen. I want it to be centered horizontally in my container, but I want to move it to the bottom of my screen. How do I edit the third line to change its position?
func addControls() {
progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default)
progressView?.center = self.view.center
view.addSubview(progressView!)
}
You could use NSLayoutConstraints and do something like this. The 3rd line being where you put the progress bar on top or beneath the other object.
var otherObject = UIView()
self.view.addSubview(progressView)
let topConstraint = NSLayoutConstraint(item: progressView, attribute: .topMargin, relatedBy: .equal, toItem: otherObject, attribute: .bottomMargin, multiplier: 1, constant: 0)
let leftConstraint = NSLayoutConstraint(item: progressView, attribute: .leftMargin, relatedBy: .equal, toItem: self.view, attribute: .leftMargin, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: progressView, attribute: .rightMargin, relatedBy: .equal, toItem: self.view, attribute: .rightMargin, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: progressView, attribute: .bottomMargin, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
self.view.addConstraints([topConstraint, leftConstraint, rightConstraint, bottomConstraint])
That's really simple.
If you want to add a subview above another one, use this function:
func insertSubview(_ view: UIView, aboveSubview siblingSubview: UIView)
To add a subview below another one, use this function:
func insertSubview(_ view: UIView, belowSubview siblingSubview: UIView)

How to put a uiview back in a stackview after I took it out?

I have a viewcontroller that holds multiple stackviews. There is a button that when pressed, the corresponding uiview wil become fullscreen inside the original view. There is a different button that is supposed to make the uiview go back to its original stackview. The uiview itself contains other views. I am having some problems doing that. The uiview does end up in the stackview, but not near the same size/place it used to be. I am not sure how to solve this, and been going at it for several hours now, looking at multiple sources.
This is the code that makes the uiview go fullscreen:
private func moveToFrontOfCardView(v: UIView) {
originalView = v.superview
if let stack = originalView as? UIStackView {
stack.removeArrangedSubview(v)
}
myCardView.addSubview(v)
let topConstraint = NSLayoutConstraint(item: v, attribute: .top, relatedBy: .equal, toItem: myCardView, attribute: .top, multiplier: 1, constant: 10)
let bottomConstraint = NSLayoutConstraint(item: v, attribute: .bottom, relatedBy: .equal, toItem: myCardView, attribute: .bottom, multiplier: 1, constant: -10)
let leftConstraint = NSLayoutConstraint(item: v, attribute: .left, relatedBy: .equal, toItem: myCardView, attribute: .left, multiplier: 1, constant: 10)
let rightConstraint = NSLayoutConstraint(item: v, attribute: .right, relatedBy: .equal, toItem: myCardView, attribute: .right, multiplier: 1, constant: -10)
myCardView.addConstraints([topConstraint, bottomConstraint, leftConstraint, rightConstraint])
}
And this is the code I use when I want it to go back:
private func moveToOriginalPosition(v: UIView) {
if let stack = originalView as? UIStackView {
stack.addArrangedSubview(v)
}
}
Does anyone have a clue how I could fix this?
EDIT
I've tried Saqib and Bilals answer, but I get this as a result:
Declare a class variable for tracking view's index
var selectedIndex = 0 // Contains Current Seleceted view's index
overrie func viewDidLoad() { ...
Before removing view from stackview get the view index like this selectedIndex = stack.subviews.index(of: v)
keep reference to all the constraints.
Before adding it back disable all the constraints topConstraint.isActive = false
Now add the view at the same index using stack.insertArrangedSubview(view, at: selectedIndex)
An other option is to create a same new view and just hide/unhide the one in stackview. StackView automatically fills the space accordingly for the hidden views.
You should deActivate the constraints you added to view when removed it from stackView, at the time you want add the view to the stackView again.
For this you should make the constraints instance of your viewController class and next, write your moveToOriginalPosition(v: UIView) method like this:
private func moveToOriginalPosition(v: UIView) {
if let stack = originalView as? UIStackView {
stack.addArrangedSubview(v)
topConstraint.isActive = false
bottomConstraint.isActive = false
leftConstraint.isActive = false
rightConstraint.isActive = false
}
}
Ofcourse, you should remove, these lines of codes from moveToFrontOfCardView(v: UIView) method:
self.topConstraint = NSLayoutConstraint(item: v, attribute: .top, relatedBy: .equal, toItem: myCardView, attribute: .top, multiplier: 1, constant: 10)
self.bottomConstraint = NSLayoutConstraint(item: v, attribute: .bottom, relatedBy: .equal, toItem: myCardView, attribute: .bottom, multiplier: 1, constant: -10)
self.leftConstraint = NSLayoutConstraint(item: v, attribute: .left, relatedBy: .equal, toItem: myCardView, attribute: .left, multiplier: 1, constant: 10)
self.rightConstraint = NSLayoutConstraint(item: v, attribute: .right, relatedBy: .equal, toItem: myCardView, attribute: .right, multiplier: 1, constant: -10)
myCardView.addConstraints([topConstraint, bottomConstraint, leftConstraint, rightConstraint])
and add them where you make your view initialized. and replace below lines with above lines in moveToFrontOfCardView(v: UIView) method:
topConstraint.isActive = true
bottomConstraint.isActive = true
leftConstraint.isActive = true
rightConstraint.isActive = true
By the looks of things you don't need to remove the original view. You could make a copy of it then display the copy full screen. Then when you dismiss this copy you release the reference to it

Resize superview with autolayout depending on largest subview

What is the best practice to resize superview with autolayout if we have inner NSView columns with dynamic heights?
For example. If we have two column layout, where left column height is bigger than right column, the superview height should be as right column height. Than, if we change right column height to be bigger than left column height, superview height should change to height of right column. How to accomplish this?
I made sample project to test this:
Initially we have layout with two columns, where .Bottom constraint of left NSView is attached to bottom of superview.
If we press Make Right Bigger button, I make height of right NSView bigger than left one.
So I want here superview to change height depending on bigger column (right column). Is there a good practice to do so?
Code:
import Cocoa
class ViewController: NSViewController {
let leftView = NSView()
let rightView = NSView()
let button = NSButton()
var rightViewHeightConstraint: NSLayoutConstraint?
override func loadView() {
self.view = TestView()
}
override func viewDidLoad() {
super.viewDidLoad()
leftView.backgroundColor = NSColor.redColor()
rightView.backgroundColor = NSColor.orangeColor()
layoutLeft(view, insertView: leftView)
layoutRight(view, insertView: rightView)
button.title = "Make Right Bigger"
button.target = self
button.action = "makeBigger:"
ViewControllerLayout.layoutBotton(view, insertView: button, bottom: -20)
}
func makeBigger(sender: AnyObject) {
rightViewHeightConstraint?.animator().constant = 150.0
}
func layoutLeft(containerView: NSView, insertView: NSView) {
insertView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(insertView)
let c1 = NSLayoutConstraint(item: insertView, attribute: .Left, relatedBy: .Equal, toItem: containerView, attribute: .Left, multiplier: 1.0, constant: 0.0)
let c2 = NSLayoutConstraint(item: insertView, attribute: .Width, relatedBy: .Equal, toItem: containerView, attribute: .Width, multiplier: 0.5, constant: 0.0)
let c3 = NSLayoutConstraint(item: insertView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100.0)
let c4 = NSLayoutConstraint(item: insertView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1.0, constant: 0.0)
let c5 = NSLayoutConstraint(item: insertView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: -60.0)
containerView.addConstraint(c1)
containerView.addConstraint(c2)
containerView.addConstraint(c3)
containerView.addConstraint(c4)
containerView.addConstraint(c5)
}
func layoutRight(containerView: NSView, insertView: NSView) {
insertView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(insertView)
let c1 = NSLayoutConstraint(item: insertView, attribute: .Right, relatedBy: .Equal, toItem: containerView, attribute: .Right, multiplier: 1.0, constant: 0.0)
let c2 = NSLayoutConstraint(item: insertView, attribute: .Width, relatedBy: .Equal, toItem: containerView, attribute: .Width, multiplier: 0.5, constant: 0.0)
let c3 = NSLayoutConstraint(item: insertView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50.0)
let c4 = NSLayoutConstraint(item: insertView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1.0, constant: 0.0)
let c5 = NSLayoutConstraint(item: insertView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: -60.0)
containerView.addConstraint(c1)
containerView.addConstraint(c2)
containerView.addConstraint(c3)
containerView.addConstraint(c4)
// containerView.addConstraint(c5) // Cant add .Bottom constraint here, because of different column sizes.
rightViewHeightConstraint = c3
}
}
struct ViewControllerLayout {
static func layoutBotton(containerView: NSView, insertView: NSView, bottom: Double) {
insertView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(insertView)
containerView.addConstraint(NSLayoutConstraint(item: insertView, attribute: .CenterX, relatedBy: .Equal, toItem: containerView, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
containerView.addConstraint(NSLayoutConstraint(item: insertView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: CGFloat(bottom)))
}
}
Download test project: GitHub
Managed to accomplish this with constraints only. Just added the container view for columns and set its height as GreaterThanOrEqual to left column and right column.
view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: leftView, attribute: .Height, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: containerView, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: rightView, attribute: .Height, multiplier: 1, constant: 0))
First create a constraint on superview with height
let heightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: greaterHeightAmongTwoColumns)
As discussed in the comment, you can post a notification and then let the super view know the updated frame. Super view would check if the updated height of any of the two columns is greater than its current height and update its heightConstraint declared above and then call
[self layoutIfNeeded]
on the superview's superview so that it is laid out with the new frame.

converting storyboard constraints into code

I'm trying to programmatically set up constraints for a class in my app so that when the keyboard appears everything moves up. i already got it working before in the storyboard, but when i take what it says in the size inspector and write it in code format, it doesn't work as expected.
...
//memo area
var memoArea = UITextView(frame: CGRectMake(20, 291, 275, 225))
memoArea.backgroundColor = majorColor
memoArea.delegate = self
self.view.addSubview(memoArea)
var memoLine = customShadow(theself: self.view, frame: memoArea.frame)
//Spacer View
var spacer:UIView = UIView(frame: CGRectMake(84, 518, 160, 6))
spacer.alpha = 0
self.view.addSubview(spacer)
//Constraints
var memoAreaToSpacer:NSLayoutConstraint = NSLayoutConstraint(item: spacer, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: memoArea, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 8)
spacerToBottom = NSLayoutConstraint(item: bottomLayoutGuide, attribute: NSLayoutAttribute.Top, relatedBy: .Equal, toItem: spacer, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(memoAreaToSpacer)
view.addConstraint(spacerToBottom)
...
so when a keyboard fires a notification this happens.
func updateBottomLayoutConstraintWithNotification(notification: NSNotification) {
let userInfo = notification.userInfo!
let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
let convertedKeyboardEndFrame = view.convertRect(keyboardEndFrame, fromView: view.window)
let rawAnimationCurve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as NSNumber).unsignedIntValue << 16
let animationCurve = UIViewAnimationOptions.init(UInt(rawAnimationCurve))
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
spacerToBottom.constant = CGRectGetMaxY(view.bounds) - CGRectGetMinY(convertedKeyboardEndFrame) - height! - 5
UIView.animateWithDuration(animationDuration, delay: 0.0, options: .BeginFromCurrentState | animationCurve, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
Here's the full app https://github.com/stanchiang/phoneHub
The code i'm talking about is in the BaseDetailViewController.swift in viewDidLoad().
The constraints i'm transferring from is the Edit Controller in the Main.storyboard file.
also, for reference i got it working through storyboard through this blog post.
http://effortlesscode.com/auto-layout-keyboard-shown-hidden/
thanks for your answers, still trying to get the hang of autolayout so general tips are welcome too.
I'm no Auto Layout expert, but I'll share what I know:
You need to turn off the AutoresizingMask for the views that you are adding constraints to:
view.setTranslatesAutoresizingMaskIntoConstraints(false)
spacer.setTranslatesAutoresizingMaskIntoConstraints(false)
memoArea.setTranslatesAutoresizingMaskIntoConstraints(false)
You are going to need a lot more constraints. I only see 2 in your code. You will need to fully constrain your layout. This includes the settings you are specifying right now with frames (width, height). Positions should probably be specified relative to other objects if you want everything to move when the keyboard shows up. When you got this working in the Storyboard, there had to be more than just 2 constraints for the entire ViewController. You'll need to bring over all of the constraints.
I suggest you add the following 6 constraints to replace the values you were setting with the frames. Put these with your other constraints. I've added the view frames in comments so that you can see where I got the values:
//var memoArea = UITextView(frame: CGRectMake(20, 291, 275, 225))
memoArea.addConstraint(NSLayoutConstraint(item: memoArea, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 275.0))
memoArea.addConstraint(NSLayoutConstraint(item: memoArea, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 225.0))
self.view.addConstraint(NSLayoutConstraint(item: memoArea, attribute: .Leading, relatedBy: .Equal,
toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 20.0))
// var spacer:UIView = UIView(frame: CGRectMake(84, 518, 160, 6))
spacer.addConstraint(NSLayoutConstraint(item: spacer, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 160.0))
spacer.addConstraint(NSLayoutConstraint(item: spacer, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 6.0))
self.view.addConstraint(NSLayoutConstraint(item: spacer, attribute: .Leading, relatedBy: .Equal,
toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 84.0))