How can I make a NSTextfield with left or right indicator for validation? - swift

I need to make a custom NSTextField with an indicator like this:
https://i.stack.imgur.com/LAhfA.png
On the right side, you could see an indicator icon.
What code I need to make this?
Thanks for all.
EDIT
The text never could be overlap the icon. The icon is not always displayed, but it can be shown when it is being written and when the text is correct, this text must also occupy the position of the icon.

A text field control is a view where the drawing is all done with an NSTextFieldCell. What you'd need to do is subclass NSTextFieldCell, and customize the drawing. Look at NSCell's API and you'll see there's a drawWithFrame:inView: method which is what does all of the drawing for the entire field. Various other methods of NSCell are used in this process.
Unfortunately some of how the drawing is done is a bit private and not eeeasily fiddled with, but the main thing is drawWithFrame:inView: will draw the background and then call drawInteriorWithFrame:inView: to draw the text. Off the top of my head, I can't remember if NSTextFieldCell uses titleRectForBounds: to determine what the text's bounds are, but I'm pretty sure it is. So you could override that to return a narrower rectangle, leaving room to either draw the validation icon with the cell itself, or use a subview.
Additionally, you'll need to adjust the bounds in which the NSTextView field editor draws and edits the text, otherwise when you view the field while it is not first responder it will look fine, but when you edit the field's text it will overlap the icon. For that you may need to adjust the frame given to editWithFrame:inView:editor:delegate:event:.
It's always a bit finicky to tweak text fields because it takes a while to find all the methods and code paths involved, but that's the gist of what you need to do.

Related

Available height to position UI elements assuming keyboard always shows

I am encountering a problem that I'm not sure how to solve. If you look at the screenshot below, you'll see that the UI is laid out so that it neatly fits into the space between the safe area layout guide's top anchor and the top of the keyboard.
The keyboard will ALWAYS be shown in this view controller. But I need a way of knowing what the height of the keyboard is so that I can do some math to figure out how to tall to make the UITextView (the red box).
I tried the approach of registering for notifications on when the keyboard will show, but that is too late.
I need a way of knowing the height of the keyboard before the view renders so that I can configure the height of each of the elements in the UI.
Is there a way to do this?
Thank you!
One option would be to capture the dimensions of the Keyboard when it IS presented then pass those dimensions into this view.
However, you will also want to make sure that you are handling cases such as the split keyboard on an iPad and things of that nature.
For that you might choose to look at the documentation on using the keyboardLayoutGuide and use it with some constraints.
https://developer.apple.com/documentation/uikit/keyboards_and_input/adjusting_your_layout_with_keyboard_layout_guide

Keep cursor position on bottom line in textView Swift

I need to create a UI where, as the user types, the cursor/typing area stays in the middle of the page and the newly typed text is pushed 'up and off' the top of the page.
I've tried to set the cursor position to the bottom of a text view which covers 0.6 of the superview but that doesn't work (presumably because it doesn't have any text?). This is a great answer for general cursor placement but my use case isn't catered for.
The code I used to try place the cursor at the end of the text view is :
func setCursorPosition() {
let newPosition = textViewOutlet.endOfDocument
textViewOutlet.selectedTextRange = textViewOutlet.textRange(from: newPosition, to: newPosition)
}
This doesn't work because it is looking for filled in text but sometimes the text view would be empty and I'd still need to load it on the bottom line.
The effect I'm trying to create would look like this :
quite a complex problem I think - any ideas?
For people who have this problem in future. I solved this by coming at it from a different angle. Rather than attempting to place the cursor half way down the page, I removed the height constraints and made the text view dynamically resize based on the content.
Then I adjusted the constraints (helped by this answer) to fix the space to the bottom safe area but didn't specify a height.
This way, the text view dynamically resizes but in an upwards direction. When it reaches the gradient I have placed over the frame it starts to fade out.
Perfect (I also disabled scrolling to make this work)
Top tip - if something seems really hard there might be a different way to approach the problem!

NSOutlineView disclosure triangle vertically off center

I'm working with an NSOutlineView on a macOS app and it provides disclosure triangles for items that can be expanded.
I'm also creating custom NSTableCellView items rather than using basic cell items. This allows me to create the cell how I want visually.
My issue is that when they're displayed, the disclosure triangle on the left is not centered vertically.
Notice how the disclosure triangles are not aligned properly. They're a bit lower than they should be. If you scroll away and come back, sometimes, they automatically align themselves correctly. Has anyone been able to fix this issue before?
For what it's worth, I'm using the following code as well for the cells.
self.outlineView.rowHeight = CGFloat(integerLiteral: 66)
self.outlineView.usesAutomaticRowHeights = true
It's hard to figure out what the problem is without seeing how you've set up your project, but I'm going to give it shot.
First, when usesAutomaticRowHeights is set to true, the outline view uses Auto Layout to position the cell views. Thus, you need to be utilizing constraints in your Storyboard or Nib file, or things will behave strangely (see: your picture). If I had to guess, the prototype cell view you set up in Interface Builder is having its autoresizingMask translated into Auto Layout constraints (which, generally, causes a boatload of problems).
What I would do is this:
Open up the Storyboard or Nib document containing the outline view.
Locate the prototype NSTableCellView instance that contains the street name text field in the Document Outline to the left of the canvas. (If you don't see the Document Outline, you can open it by clicking the item at Editor » Show Document Outline in the main menu).
Next, see if you have any constraints in place. If you do, remove them by selecting Editor » Resolve Auto Layout Issues » Clear Constraints under the menu item "section" that's titled All Views in ${YOUR_SCENE}.
Now, depending on what you're going for, there are different ways to go about setting up constraints, but here's what I would suggest. Assuming you want the street name to be centered vertically with the disclosure triangle, I would add a vertical constraint between the text field and its parent cell view like so:
With the text field selected in the Document Outline, click the Align icon in the lower right-hand corner of Interface Builder's main canvas area (see image).
In the popover that appears, check the checkbox next to Vertically in Container.
In the text field on the right side of the popover, enter a value of “0”.
Finally, click the “Add 1 Constraint” button.
You’ll probably see a red error (or yellow warning) sign show up, as the view has now opted into Auto Layout, but it only has a metric for its vertical position. So we now need to add some constraints to describe where the text field should be positioned on the x axis. Like before, we’ll define the constraints using the popover buttons on the lower right-hand side of the canvas:
Click the Add New Constraints button (the one to the right of the Align button).
On the diagram at the top of the popover, click the faint red lines on the left and right side of the white rectangle. This is telling Interface Builder we want to add leading and trailing constraints.
Now, enter the desired padding you want on each side of the text field. In the example image, I went with “4” points on both sides, but obviously, you can use whatever value(s) you think works best with your layout.
Finally, click the “Add 2 Constraints” button.
Any warning(s) that were present should now disappear, as we've added enough constraints to describe the position of the text field. In theory, you should now be able to build and run your project, and the text fields should be aligned with the disclosure triangles. With that said, there are plenty of other reasons a layout can get finicky, and considering usesAutomaticRowHeights is a new API in macOS High Sierra (and Steve Jobs is no longer there to beat it into Apple developers to make everything Just Work™), there could be issues that I'm unaware of.
Alternatively, you can set usesAutomaticRowHeights to false and have some object (e.g. a view controller, a NSObject subclass, etc.) conform to the NSOutlineViewDelegate protocol and implement the outlineView(_:heightOfRowByItem:) method to return any arbitrary height you want for different rows. The nice thing about sizing rows this way is that you can allow certain rows to be larger or smaller, depending on the role of the corresponding item. There are lots of tutorials on this, so I won't regurgitate a half-baked explanation here, but feel free to Google “Conforming to NSOutlineViewDelegate protocol” for more info.
Anyway, try the steps above, and see if they do anything for you, and if they don't, let me know. I can go as deep into the rabbit hole with you as you need, so just ask. Good luck!
For those like me who stumbled upon this issue many years later, here's the fix that worked for me, and requires a lot less work.
NSOutlineView has a function frameOfOutlineCell(atRow:) and the documentation states: You can override this method in a subclass to return a custom frame for the outline button cell
You can override the method in order to provide a frame that's actually in the vertical center of the row. And an important point that I learned from trial and error, is that you don't even need to provide that updated frame. Not sure if this is a bug or what, but for me, just calling super.frameOfOutlineCell(atRow: row) in the function override was enough to make the disclosure indicator appear in the correct location.
So my subclass of NSOutlineView is this:
class MyOutlineView: NSOutlineView {
override func frameOfOutlineCell(atRow row: Int) -> NSRect {
super.frameOfOutlineCell(atRow: row)
}
}
That's all. Hopefully that works for others as well!

UIActionSheet truncates long strings! Alternatives?

I have a UIActionSheet which gives the user a few standard choices. The text on the buttons, however, does not cleverly scale down like a text field though when there's too much-- it just truncates with an ellipsis.
I need to say a little more in on of my action sheet buttons than there's room for. I don't see any way of changing the action sheet's behavior, unfortunately. Any thoughts on alternatives?
Thanks!
You could put some of the descriptive text in the UIActionSheet's title property, and then give just the verb or something concise in the button titles.
One alternative is: you might want to create a full-screen view that you show with presentModalViewController:animated:, where you have more space to show the text.
A third alternative is to create a UIView that animates up with UIButtons that you can customize, but doesn't fill the entire screen. I do that with some of my apps where the Settings are in a tab that slides up but doesn't need to cover the entire screen.

Easy way to scroll overflow text on a button?

Does anyone have any examples or resources where i might find information on scrolling text which is too long to display in a button control? I'm thinking something along these lines.
Display as much text will fit within the current rect with a '...' at the end to signify overflow.
Pause for say 1 second then slowly scroll the text to the right edge displaying the right part of the string.
Display as much text will fit within the current rect with a '...' at the beginning to signify overflow.
Start the whole thing over in reverse.
Is there an easy way to do this using the "core" or built in "animation" frameworks on a certain mobile device?
[edit]
Iwanted to add some more details as i think people are more focused on wether or not what i'm trying to accomplish is appropriate. The button is for the answers on a trivia game. It does not perform any speciffic UI function but is for displaying the answer. Apple themselves is doing this in their iQuiz trivia game on the iPod Nano and i think its a pretty elegant solution to answers that are longer than the width of my button.
In case its the '...' that is the difficult part of this. Lets say i removed this requirement. Could i have the label for the button be full sized but clipped to the client rect of the button and use some animation methods to scroll it within the clipping rect? This would give me almost the same effect minus the ellipses.
Here's an idea: instead of ellipses (...), use a gradient on each side, so the extra text fades away into the background color. Then you could do this with three CALayers: one for the text and two for fade effect.
The fade masks would just be rectangles with a gradient that goes from transparent to the background color. They should be positioned above the text layer. The text would be drawn on the text layer, and then you just animate it sliding back and forth in the manner you describe. You can create a CGPath object describing the path and add it to a CAKeyframeAnimation object which you add to the text layer.
As for whether you think this is "easy" depends on how well you know Core Animation, but I think once you learn the API you'll find this isn't too bad and would be worth the trouble.
Without wishing to be obtuse, maybe you should rethink your problem. A button should have a clear and predictable function. It's not a place to store and display text. Perhaps you could have a description show on screen with a nice standard button below?
Update with source code example:
Here is some ready to use source code example (actually a full zipped Xcode project with image and nib files and some source code), not for the iPhone, not using Core Animation, just using a couple of simple NSImages and a NSImageView. It is just a cheap hack, it does not implement the full functionality you requested (sorry, but I don't feel like writing your source code for you :-P), horrible code layout (hey, I just hacked this together within a couple of minutes, so you can't expect any better ;-)) and it's just a demonstration how this can be done. It can be done with Core Animation, too, but this approach is simpler. Composing the button animation into a NSImageView is not as nice as subclassing a NSView and directly paint to its context, but it's much simpler (I just wanted to hack together the simplest solution possible). It will also not scroll back once it scrolled all the way to the right. Therefor you just need another method to scroll back and start another NSTimer that fires 2 seconds after you drew the dots to the left.
Just open the project in Xcode and hit run, that's all there is to do. Then have a look at the source code. It's really not that complicated (however, you may have to reformat it first, the layout sucks).
Update because of comment to my answer:
If you don't use Apple UI elements at all, I fail to see the problem. In that case your button is not even a button, it's just a clickable View (NSView if you use Cocoa). You can just sub-class NSView as MyAnswerView and overwrite the paint method to paint into the view whatever you wish. Multiline text, scrolling text, 3D text animated, it's completely up to your imagination.
Here's an example, showing how someone subclassed NSView to create a complete custom control that does not exist by default. The control looks like this:
See the funny thing in the upper left corner? That is a control. Here's how it works:
I hate to say that, as it is no answer to your question, but "Don't do that!". Apple has guidelines how to implement a user interface. While you are free to ignore them, Apple users are used to have UIs following these guidelines and not following them will create applications that Apple users find ugly and little appealing.
Here are Apple's Human Interface Guidelines
Let me quote from there
Push Button Contents and Labeling
A push button always contains text, it
does not contain an image. If you need
to display an icon or other image on a
button, use instead a bevel button,
described in “Bevel Buttons.”
The label on a push button should be a
verb or verb phrase that describes the
action it performs—Save, Close, Print,
Delete, Change Password, and so on. If
a push button acts on a single
setting, label the button as
specifically as possible; “Choose
Picture…,” for example, is more
helpful than “Choose…” Because buttons
initiate an immediate action, it
shouldn’t be necessary to use “now”
(Scan Now, for example) in the label.
Push button labels should have
title-style capitalization, as
described in “Capitalization of
Interface Element Labels and Text.” If
the push button immediately opens
another window, dialog, or application
to perform its action, you can use an
ellipsis in the label. For example,
Mail preferences displays a push
button that includes an ellipsis
because it opens .Mac system
preferences, as shown in Figure 15-8.
Buttons should contain a single verb or a verb phrase, not answers to trivia game! If you have between 2 and 5 answers, you should use Radio Buttons to have the user select the answer and an OK button to have the user accept the answer. For more than 5 answers, you should consider a Pop-up Selector instead according to guidelines, though I guess that would be rather ugly in this case.
You could consider using a table with just one column, one row per answer and each cell being multiline if the answer is very long and needs to break. So the user selects a table row by clicking on it, which highlights the table cell and then clicks on an OK button to finish. Alternatively, you can directly continue, as soon as the user selects any table cell (but that way you take the user any chance to correct an accidental click). On the other hand, tables with multiline cells are rather rare on MacOS X. The iPhone uses some, but usually with very little text (at most two lines).
Pretty sure you can't do that using the standard API, certainly not with UILineBreakMode. In addition, the style guide says that an ellipsis indicates that the button when pressed will ask you for more information -for example Open File... will ask for the name of a file. Your proposed use of ellipsis violates this guideline.
You'd need some custom logic to implement the behaviour you describe, but I don't think it's the way to go anyway.
This is not a very good UI practice, but if you still want to do it, your best bet is to do so via a clickable div styled to look like a button.
Set the width of the div to an explicit value, and its overflow to hidden, then use a script executing on an interval to adjust the scrollLeft property of this div.