I created a custom keyboard screen on tvOS.
If possible, tap on UITextField as it is, I want to transition to the custom keyboard view.
But tapping the UITextField always displays the system keyboard.
What should I do now?
1) Make the view controller implement this delegate: UITextFieldDelegate
class YourViewController: UIViewController, UITextFieldDelegate {
// ...
yourTextField.delegate = self
// ...
}
2) Return false in textFieldShouldBeginEditing, so the text field doesn't respond and the keyboard doesn't open. Instead, open yours or do whatever you want.
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
// HERE, open your keyboard or do whatever you want
return false
}
textField.inputView = UIView()
class YourViewController: UIViewController,UITextFieldDelegate { }
First set your delegate for textfieldtextField.delegate = self, Then
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.addTarget(self, action: #selector(gettextFieldFunction), for: UIControlEvents.touchDown)
}
Related
I am new to Mac OSX and with Apple promoting the fact that the bodies of code are becoming similar decided to tell the folk I am writing code for we should be able to do a Mac OSX version. iPhone and iPad versions are all good and about to release second version so no issues there.
So I am subclassing NSWindowController to get access to the Toolbar and worked out how to remove and add items on the toolbar, but for the life of me I can not get one NSViewController (firstViewController) to dismiss and bring up the second NSViewController (secondViewController) in the same NSWindowController.
So the 2 issues are that
1. I want to be able to performSegueWithIdentifier from the first NSViewController in code and
2. bring up the second NSViewController by replacing the first NSViewController in the same NSWindowController.
If I add a button to the firstViewController and put a segue to the secondViewController then when I select the button the secondViewController comes up just fine but in a seperate window not the same NSWindowController that I want it to and the firstViewController does not get replaced but stays in the NSWindowController.
So I know the segue idea will work but its not working in code and when I do insert the segue from a button it works but into a seperate NSViewController that is not part of the NSWindowController.
I am trying to find some programming guide from Apple on the issue but no luck so far.
Here is an overview from my Storyboard:
Here is my NSWindowController subclassed and the func loginToMe2Team is trigger from the NSToolBar and its working just find as the print statements show up on the console.
import Cocoa
class me2teamWindowsController: NSWindowController {
#IBOutlet var mySignUp : NSToolbarItem!
#IBOutlet var myToolbar : NSToolbar!
let controller = ViewController()
override func windowDidLoad() {
super.windowDidLoad()
print("window loaded")
}
override func windowWillLoad() {
print("window will load")
}
#IBAction func logInToMe2Team(sender: AnyObject){
controller.LogIn() //THIS IS THE FUNC I AM TESTING WITH
}
#IBAction func signUpToMe2Team(sender: AnyObject){
controller.signUp()
}
Here is my NSViewController subclassed with the func LogIn. Its getting selected just fine but the performSegueWithIdentifier is not. And I did cut and past the Identifier to make absolutely sure it was the same.
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var theWebPage: WebView!
#IBOutlet weak var progressIndicator: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://thewebpage.com.au"
self.theWebPage.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
}
override func viewDidAppear() {
}
func LogIn() {
print("I logged in")
self.performSegueWithIdentifier("goToTeamPage", sender: self)
//THIS IS THE BIT THATS NOT WORKING
}
func signUp() {
print("I have to sign up now")
}
override var representedObject: AnyObject? {
didSet {
}
}
func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!)
{
self.progressIndicator.startAnimation(self)
}
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!)
{
self.progressIndicator.stopAnimation(self)
}
}
You need to use a custom segue class (or possibly NSTabViewController if it’s enough for your needs). Set the segue’s type to Custom, with your class name specified:
…and implement it. With no animation, it’s simple:
class ReplaceSegue: NSStoryboardSegue {
override func perform() {
if let src = self.sourceController as? NSViewController,
let dest = self.destinationController as? NSViewController,
let window = src.view.window {
// this updates the content and adjusts window size
window.contentViewController = dest
}
}
}
In my case, I was using a sheet and wanted to transition to a different sheet with a different size, so I needed to do more:
class ReplaceSheetSegue: NSStoryboardSegue {
override func perform() {
if let src = self.sourceController as? NSViewController,
let dest = self.destinationController as? NSViewController,
let window = src.view.window {
// calculate new frame:
var rect = window.frameRectForContentRect(dest.view.frame)
rect.origin.x += (src.view.frame.width - dest.view.frame.width) / 2
rect.origin.y += src.view.frame.height - dest.view.frame.height
// don’t shrink visible content, prevent minsize from intervening:
window.contentViewController = nil
// animate resizing (TODO: crossover blending):
window.setFrame(window.convertRectToScreen(rect), display: true, animate: true)
// set new controller
window.contentViewController = dest
}
}
}
I want to show/hide a window in swift by clicking a button from main window. Beginsheet is showing the window, but endsheet is not closing the window. My appdelegate code is given:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
var settingsController: SettingsController?
#IBAction func inSettings(sender: NSObject?)
{
settingsController = SettingsController(windowNibName: "SettingsController")
window.beginSheet(settingsController!.window!, completionHandler: nil)
}
#IBAction func outSettings(sender: NSObject?)
{
window.endSheet(settingsController!.window!)
}
}
SettingsController:
import Cocoa
class SettingsController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
Swift 3 Solution:
Lets say that you have WindowA and WindowB. You want to open WindowB but first You want to hide WindowA.
Connect windows with a segue. (Select "Show" as segues "Kind" property) And you need a static class to keep hidden window. in WindowA override shouldPerformSegue and keep WindowA as a static NSWindow object.
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
YourStaticClass.WindowA = self.view.window
self.view.window?.orderOut(self)
return true
}
orderOut(self) hides the window. Then WindowB will be opened.
In WindowB's view controller use a function to close windowB and show hidden WindowA:
#IBAction func btnBack_Click(_ sender: NSButton) {
YourStaticClass.WindowA?.makeKeyAndOrderFront(YourStaticClass.WindowA)
self.view.window?.close()
}
Use endSheet to end a document-modal sheet session. Like this:
#IBAction func outSettings(sender: NSObject?)
{
settingsController!.window!.endSheet(settingsController!.window!)
}
EDIT: You need to actually close the window in your completion handler you call orderOut, like this:
#IBAction func inSettings(sender: NSObject?)
{
settingsController = SettingsController(windowNibName: "SettingsController")
window.beginSheet(settingsController!.window!) {
settingsController!.window!.orderOut(nil)
}
}
How do I dismiss the keyboard by pressing the return key on device? I know how to dismiss keyboard, but not when using the UITextView:
resignFirstResponder
I have tried this, but it does not work:
self.messageTextView.delegate = self
And with this function:
func messageTextViewShouldReturn(textView: UITextView) -> Bool
{
self.messageTextView.resignFirstResponder()
return true
}
Remember to add the UITextDelegate into ViewDidLoad()
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n"
{
textView.resignFirstResponder()
return false
}
return true
}
Swift 5
unlike a textField where IBActions are available, there are no actions available for text views.
create your textViewOutlet
If you are using a tableview:
identify where your textView row is located:
let textViewIndex = IndexPath(row: 0, section: 1)
then in (_:didSelectRowAt:) dismiss the keyboard if any row other than your textView
if indexPath != textViewIndex {
textViewOutlet.resignFirstResponder()
}
if you are not using a tableview: In your SB viewcontroller, drag a UITapGestureRecognizer to your view. Then create an IBAction from that Tap Gesture Recognizer by control dragging it to your view. In the action dismiss your keyboard from your textViewOutlet:
#IBAction func tapGestureRecognizer(_ sender: Any) {
notesField.resignFirstResponder()
}
I have a NSViewController named Hardness, and I need not to let user resize it. Of course, I can just resize it back every time the users tries, but is there any way just not to let user open a window to full screen, or to stretch the window?
edit/update: Xcode 10.2 • Swift 5
NSWindow has a property called styleMask that allows you to control what kinds of control will be available to the user. If you don't want to allow the user to resize the window you have to remove the style mask .resizable using the mutating method remove(member: NSWindowStyleMask). To enable it again you need to use the mutating method insert(member: NSWindowStyleMask). Note that it will also disable the full screen mode for that window:
removing to disable:
window.styleMask.remove(.resizable)
inserting to enable
window.styleMask.insert(.resizable)
Sample
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var closable: NSButton!
#IBOutlet weak var miniaturizable: NSButton!
#IBOutlet weak var resizable: NSButton!
#IBOutlet weak var titled: NSButton!
lazy var window: NSWindow! = self.view.window
func remove(_ member: NSWindow.StyleMask) {
window.styleMask.remove(member)
}
func insert(_ member: NSWindow.StyleMask) {
window.styleMask.insert(member)
}
#IBAction func toggle(_ sender: NSButton) {
switch sender.state {
case .on:
switch sender {
case closable: insert(.closable)
case miniaturizable: insert(.miniaturizable)
case resizable: insert(.resizable)
case closable: insert(.closable)
case titled: insert(.titled)
default: break
}
case .off:
switch sender {
case closable: remove(.closable)
case miniaturizable: remove(.miniaturizable)
case resizable: remove(.resizable)
case closable: remove(.closable)
case titled: remove(.titled)
default: break
}
default: break
}
}
}
Sample Project
I solved the same issue with the non-resizable window by one line of code in
override func viewDidAppear() {
self.view.window?.styleMask.remove(NSWindowStyleMask.Resizable)
}
The correct approach would be to use bitwise operators.
Disable resize:
window?.styleMask &= ~NSResizableWindowMask
Enable resize:
window?.styleMask |= NSResizableWindowMask
This answer may be of some help in addition to the current one. There's also a nice simple way to accomplish this by using setHidden with NSWindowZoomButton
Setup the functionality as a sub-class of NSWindow:
Objective-C
#import "CustomWindow.h"
#implementation CustomWindow
- (void)awakeFromNib {
NSButton *zoomButton = [self standardWindowButton:NSWindowZoomButton];
[zoomButton setHidden:YES];
}
#end
Swift
import CustomWindow
class CustomWindow {
func awakeFromNib() {
var zoomButton: NSButton = self.standardWindowButton(NSWindowZoomButton)
zoomButton.setHidden(true)
}
}
Connect the custom class to your window in IB and the Zoom button should be now hidden!
A little more elegant solution for Swift 3, so that the | operator can be used:
public func | (left: NSWindowStyleMask, right: NSWindowStyleMask) -> NSWindowStyleMask {
return NSWindowStyleMask(rawValue: left.rawValue | right.rawValue)
}
How can I detect an end editing action on a NSTextView, just like on NSTextField ? I can not see it as an action or in its delegate.
You can register for notifications, such as NSTextDidEndEditingNotification.
If you want to use the delegate pattern, then you should check the NSTextDelegate protocol. Docs here. The method sent on end editing is textDidEndEditing:.
NSTextView is a subclass of NSText, so it is a good idea to check the docs for that class, too.
Example
NSTextView has a NSTextViewDelegate property you can use to be notified about changes. The delegate methods are mere convenience methods to obtain the "end editing" notification, unlike control:textShouldEndEditing you may know from NSTextField, for example.
class SomeViewController: NSViewController, NSTextViewDelegate {
var textView: NSTextView!
func loadView() {
super.loadView()
textView.delegate = self
}
func textDidBeginEditing(notification: NSNotification) {
guard let editor = notification.object as? NSTextView else { return }
// ...
}
func textDidEndEditing(notification: NSNotification) {
guard let editor = notification.object as? NSTextView else { return }
// ...
}
}