Keep cursor position on bottom line in textView Swift - 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!

Related

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

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.

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!

UIStackView and Multiline Labels?

I've tried to get this to work but interface builder is doing my head in and I was wondering if anyone has a proper solution for this.
So I want to have a stackview that contains a label with multiple lines inside. The first hit on google (read here) tells you to embed the label within a view (A), then drag that view into another view (B) (because the embedded view (A) has a 20pixel pad) and then unembed the first view (A).... voila. Except this only tricks the stackview for horizontal stacks and if you continue to stack the view you will still have a ton of problems (I will demonstrate with screenshots later in the question).
I found another guide on google that criticizes a potential fix for the problem, fixing the stackviews width. The author makes the point that Apple didn't intend for you to be doing that, after all it's supposed to be auto layout, not fixed layout. This guide theorises that the issue is just a bug and that you can create a stackview with a single line label, set it all up and THEN add the multiple lines. I tried this and it didn't work, it simply messed the entire stack view up! The stack view will warp and essentially break unless the label has number of lines set to 1 and only 1. (Image 1) Stackview with label set to have multiple lines.
So I talked earlier about embedding the paragraph label within a view. This doesn't cause any errors in the storyboard,(Image 2) you can't really align the text properly with the other UIStacks but that's not an immediate problem for me to solve. What IS a problem is what happens at runtime....
Simulator, Portrait (Image 3), Simulator, Landscape (Image 4).
I tried running this on an actual device to see if it was just a simulator bug but the same thing happened on my iphone 6. Safe to say this is probably not going to work!
Oh and just before we go any further, I am building the stack views in the following way:
[name - placeholder]
[phone - placeholder]
[address - placeholder]
, setting a spacing of 8 and equal fill
,vertically stacking all of these stacks (3 into 1) and setting a spacing of 8
, vertically stacking the details titles with the big stack and 8 spacing
,finally adding the title and button into the stack view with a spacing of 32.
I then apply some storyboard constraints: in this case just centre vertically & horizontally, so the view is always centred and displays properly in both screen orientations.
Even though this isn't aligned properly, this is the view before applying the stacks and constraints, this is what I want my endgame to look like: Looks kind of silly, but I want to figure this out so I can actually stack my paragraphs! (Image - 5).
So now hopefully I've established that you can't really embed the label within a view as it doesn't render correctly at runtime, and you can't trick the stack into adding new lines.
How do I put a label with multiple lines into a stack view safely?
This is almost an offshoot question but when you try applying a stack to a paragraphed label, it sets the width of the label to be absolutely massive (sometimes it throws an error that interface builder can't render it Demonstrated here (Image 6). I've seen this happen a few times and don't really understand how xcode thinks that is a sensible option.
I don't want to apply fixed widths to my labels or stacks because I'll only be left with another warning, and warnings are bad!
I'm pretty lost at what to do, if anyone knows of a way this can be achieved I would be eternally grateful!
Thanks
This really seems to be a bug.
A workaround that works for me is embedding the multiline label in a view and leaving it there.
That fixes the layout on the Storyboard editor and also works in the simulator.
A weird thing is that if I have several multiline labels on the same StackView I only have to embed one of them in a UIView, and then all the other multiline labels will behave properly.
While I do agree this is an issue in UIStackView as layouting should work according to the intrinsic size of the UILabel.
When using stackview with multiline label, it is not able to update its size according to the label.
For resolving this issue, use preferredMaxLayoutWidth property of the label and set it to any value.
label.preferredMaxLayoutWidth = 1
Note: This even worked for me when I set it to 1
The preferredMaxLayoutWidth property as defined in the Apple Docs:
This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text flows to one or more new lines, increasing the height of the label.
which we do want to increase for a vertical UIStackView.
the solution is about embedding the UILabel inside "view without inset".
and then update your constraints.

Swift - Auto constraints

I am trying to use the auto size classes from the storyboard on xcode 7 to position UI elements in a controller. The problem that I'm running into is that when I try to use the "Add missing constraints" function (located at the bottom right corner of the console), it positions my UI elements correctly except for the last elements (pictures describe better). The first image below shows the storyboard file where I just want 3 buttons (stacked above eachother) to be the same width and length to be on the top right corner of any screen.
However, when I add constraints and run the simulations, it seems like the top two buttons are positioned correctly with the correct length and width but the third button is out of place (image below).
So my question is, am I forgetting a step to make all buttons position themselves? Or should I try to convert everything to a percentage and place UI elements based on the percentage of the screen (if so, how would I go about doing that)?
I've also tried adding another blank button (removing the button label) underneath the 3rd button and adding constraints like that but it didn't work for me. Let me know if you have any suggestions, thanks!
In you case, Autolayout the constraints you need to give to UIButton is 4 constrains.
Leading
Trailing
Width
Height
If you miss any of them, then surely you will get an error. So, what's your error is?
To the third UIButton, you have not given the height, while to the above two buttons you have given.
So, just remove the bottom constraint of UIButton and give the equal height to above UIButton.
FYI, never use Add Missing Constraints without any confirmation from your side.
Update:
Check this video to remove trailing or leading margin:
http://sendvid.com/1h8deg18
You can actually see the solution in action if you use the Preview screen while setting up your auto layout constraints. I just created a similar view and buttons and stepped through the process. I coloured the buttons and named them to make things obvious.
I added the three buttons. At this point, none of the buttons show up in the preview.
I then setup the auto layout constraints for Button1. If you want the buttons anchored to the top right, then you don't need to worry about the leading constraint. You need width, height, top, and trailing.
Now Button1 will snap to it's position in the top right corner of the preview screen.
Now do the same thing for Button2. Set width, height, top (vertical space to Button1), and trailing.
Button2 will now snap into place in the preview.
Now the same thing again for Button3. You anchored the first button to the top right of the screen. Then Button2 to the bottom of Button1 and the right edge of the screen. Then again for Button3. You could also align the edges of the 2nd and 3rd buttons, if you prefer that to trailing space.
Now you'll see in the preview that your buttons are correctly positioned, regardless of device.
As long as you specify height and width for each button, you don't need to worry about the left edge or the bottom edge of the screen at all. They each know to "stick" to the top right and they know what size to be.
** Note: If you're not familiar with the "Preview" option...
With your storyboard open, hold Option and select storyboard again to get another copy of the storyboard on the right side. Highlight the view controller you are interested in on the left side. On the right side, select the Preview option as shown below.
Now you have your storyboard and the preview side by side, so you can see the exact impact of any auto layout changes you make. You can also add or remove devices to the preview.

is there any method to get the row and column number in a uitextview

I am trying to achieve a task in which the user the will create notes just like iNotes.app, for this i have to give some padding from left, in my case the padding is little more than the actual iNotes(app) and the problem with this is, If I complete the whole line it goes out of view/screen and user cant see.
To solve this Issue I first I used
UIEdgeInsetsMake(0,40,0,-40);
//this thing makes the content non-scrollable horizontaly
//but the text still goes out of screen
Then I used
UIEdgeInsetsMake(0,40,0,0);
//By doing this the content becomes horizontally
//scrollable and the content appear as per scrolling.
I don't want my textview to scroll Horizontally and I want it to show the content without cutting anything.
Please guide my what should I do to tackle this problem and
If my approach is wrong please suggest any other way. Thanks in Advance :)