2017-01-09 7 views
1

New to Swift.텍스트 필드를 편집하는 동안 키보드를 제외한 UI와의 사용자 상호 작용을 금지합니다.

사용자가 입력을 시작하기 위해 텍스트 필드를 클릭하면 해당 텍스트 필드에 입력하는 것 이외의 모든 사용자 상호 작용을 비활성화 할 수 있습니까? 나는 사용자가 텍스트 필드 바깥을 클릭 할 수 없도록하고 반환 키를 눌러 사용자 상호 작용이 다시 활성화되는 키보드를 닫아야합니다. 키보드 부분을 설정 해제했습니다.

isUserInteractionEnabled 함수는 모든 상호 작용을 중지 할 수 있지만 여전히 사용자가 키보드와 상호 작용할 수 있기를 바랍니다.

감사

+0

자동으로 실행하면 안됩니다. 프로그래밍을 통해 다른 모든 기능을 사용하지 않도록 프로그래밍해야합니다. –

+0

오른쪽. 그게 어떻게 해야할지 궁금해하는거야. userInteractionEnabled가 모든 상호 작용을 중지 할 수 있지만 여전히 사용자가 키보드와 상호 작용할 수 있기를 원합니다. – brownmamba

+0

예를 들어 UI 버튼의 경우 yourButtonName을 수행해야합니다.isEnabled = false –

답변

0

당신이 설명하는 동작은 UI 요소의 경우 부울 isEnabled 값을 조작하여 수행 할 수있다. 이것을 매끄럽고 사용자 친화적으로 만드는 몇 가지 단계가 있습니다.

그냥 좋은 방법은,이 예를 들어 필요하지 않습니다,하지만 난의 MyViewController의 확장을 구독하는/키보드 알림 취소 좋아하고 그래서 거기에, 그래서 같은 :

import Foundation 
import UIKit 

extension MyViewController {    

    //MARK: Subscribing/Unsubribing to NotificationCenter. 
    func subcribeToKeyboardNotifications(){  
     NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
     NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
    } 

    func unsubscribeToKeyboardNotifications(){ 
     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
    } 

    //MARK: Screen manipulation methods, to move the UIView up when the bottom text field is editing. 
    func keyboardWillShow(_ notification: Notification) { 
     if bottomTextField.isEditing { 
      view.frame.origin.y = getKeyboardHeight(notification) * -1 
     } 
    } 

    func keyboardWillHide(_ notification: Notification) { 
     if bottomTextField.isEditing { 
      view.frame.origin.y = 0 
     } 
    } 

    //MARK: Value returning method to calculate keyboard height. 
    private func getKeyboardHeight(_ notification: Notification) -> CGFloat { 
     let userInfo = (notification as NSNotification).userInfo! 
     let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue 
     return keyboardSize.cgRectValue.height 
    } 
} 

다음, MyViewController에서 리턴 키를 누를 때 키보드를 resignToFirstResponder()으로 설정하고 내 UITextFieldDelegates을 설정했는지 확인합니다.

import Foundation 
import UIKit 

class MyViewController: UIViewController, UITextFieldDelegate { 
    @IBOutlet weak var someButton: UIButton! 
    @IBOutlet weak var topTextField: UITextField! 
    @IBOutlet weak var bottomTextField: UITextField! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     //Set the delegates to self, it this example. 
     topTextField.delegate = self 
     bottomTextField.delegate = self 
     enableUIElements(true) 
    } 

    //Delegate function to type stuff into the text field. 
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     enableUIElements(false) 
     var newText = textField.text! as NSString 
     newText = newText.replacingCharacters(in: range, with: string) as NSString 
     let textSize: CGSize = newText.size(attributes: [NSFontAttributeName: textField.font!]) 
     return textSize.width < textField.bounds.size.width 
    } 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     textField.resignFirstResponder() //Dismiss the keyboard. 
     enableUIElements(true) //enable the UI elements. 
     return true 
    } 

    //Create a function to enable/disable UI elements. 
    func enableUIElements(_ enable: Bool){ 
     someButton.isEnabled = enable 
     //TODO: add other elements here. 
    } 
} 

마지막 기능 !!! 키보드를 활성화 한 상태에서 다른 요소를 활성화/비활성화하려면이 방법을 사용하십시오. 당신이 UITextField에 인스턴스에 초점을 맞추고있는 동안보기에

1

그래서, 나에게 온 첫번째 생각은 모든 UI 요소를 사용하지 않도록한다 :) 갈 필요가 어디를 가야

.

UI 요소를 인수로 가져 오는 함수를 만듭니다 (예 : UITextField, ex). 함수의 본문에서 모든 UI 요소를 검사하고 주기적으로 모든 사용자를 사용하지 않도록 설정하면 전달 된 인수와 같지 않습니다. 텍스트 필드에서 유형 및 텍스트를 추가로 확인할 수 있습니다.

다음은 함수의 신체의 초안입니다 :

func disableAll(exceptInput element: UITextField) { 
    for item in self.view.subviews { 
     if item != element { 
      item.isUserInteractionEnabled = false 
     } else { 
      item.isUserInteractionEnabled = true 
     } 
    } 
} 

을 그리고 예를 들어, 텍스트 필드의 행동에이 방법을 수행합니다. onDidStart에 있습니다.

그리고 분명히 사용자 상호 작용을 위해 모든 요소를 ​​사용하도록 설정하는 것을 잊지 마십시오. 코드는 간단하다 : 당신이 모든 UITextField에 대한 onDidEnd IBAction를에서 수행 할 수있는

func enableAll() { 
    for item in self.view.subviews { 
     item.isUserInteractionEnabled = true 
    } 
} 

이 방법. 마지막 단계는 정상적인 응용 프로그램 동작을 실행하려는 경우 필요합니다.

+0

이것은 내가 달성하고자하는 것에 매우 가깝습니다. 나는 테이블 뷰 셀로 작업하고 있으며 모든 셀을 제어하기 위해 하나의 textField 요소가 있습니다. 따라서 사용자가 다른 셀의 textField를 눌러서 상호 작용을 활성화 할 수 있습니다. 한 셀의 textField에 초점을 맞출 방법이 있습니까? 그래서 그들은 다른 텍스트 필드를 클릭 할 수 없습니까? – brownmamba