2017-04-14 4 views
0

사용자가 버튼을 누르고 입력을 입력 할 수있는 곳에서 경고를 볼 수있게하려고합니다 (서비스 가격 설정). 다른 논리는 데이터를 데이터베이스에 저장하는 것과 관련이 있으며 이는 내 문제와 관련이 없습니다.스위프트 : UITextField가 인식되지 않습니다.

나는 다음과 같은 예를 사용하고 있습니다 : 그것은 확실히 제대로 경고를 보여줍니다 점에서, 작동

https://stackoverflow.com/a/30139623/2411290

을,하지만 난

print("Amount: \(self.tField.text)") 

"self.tField.text"를 포함하면 인식되지 않습니다. 내가 얻을 특정 오류 : 유형의

값 'testVC은'더 멤버 'TField 객체'

@IBAction func setAmount(_ sender: Any) { 

    var tField: UITextField! 


    func configurationTextField(textField: UITextField!) 
    { 
     print("generating textField") 
     textField.placeholder = "Enter amount" 
     tField = textField 

    } 

    func handleCancel(alertView: UIAlertAction!) 
    { 
     print("Cancelled") 
    } 

    let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert) 

    alert.addTextField(configurationHandler: configurationTextField) 
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:handleCancel)) 
    alert.addAction(UIAlertAction(title: "Done", style: .default, handler:{ (UIAlertAction) in 
     print("Done !!") 

    })) 
    self.present(alert, animated: true, completion: { 
     print("completion block") 
     print("Amount: \(self.tField.text)") // Error here 


    }) 

    //// other logic for app 
} 

답변

2

tFieldsetAmount 함수 내부의 지역 변수가 없습니다. 그것은 클래스의 속성이 아닙니다.

변경 :

self.tField.text 

에 :

tField.text 

로컬 변수에 액세스 할 수 있습니다.

하지만이 질문에서 지역 변수 UITextField을 작성하는 이유는 무엇입니까? 텍스트 필드가 어디에도 사용되지 않을 때 텍스트를 인쇄하는 이유는 무엇입니까?

대개 "완료"버튼에 대한 작업 처리기의 경고 텍스트 필드에 액세스해야합니다. 경고를 표시하는 완료 블록에서 아무 것도 할 필요가 없습니다.

@IBAction func setAmount(_ sender: Any) { 
    let alert = UIAlertController(title: "Set price of service", message: "", preferredStyle: .alert) 

    alert.addTextField(configurationHandler: { (textField) in 
     print("generating textField") 
     textField.placeholder = "Enter amount" 
    }) 

    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action) in 
     print("Cancelled") 
    }) 

    alert.addAction(UIAlertAction(title: "Done", style: .default) { (action) in 
     print("Done !!") 
     if let textField = alert.textFields?.first { 
      print("Amount: \(textField.text)") 
     } 
    }) 

    self.present(alert, animated: true, completion: nil) 
} 
+0

정말 감사드립니다. 감사합니다. 몇 가지 전역 변수 인 price와 tField (UITextField)를 만들었습니다. "Done"핸들러 안에있는 모든 로직을 처리 할 수는 없기 때문에 경고의 바깥에있는 Firebase 데이터베이스에 한 번에 5-6 개의 값을 입력하기 때문에 가격의 값을 저장해야합니다. – user2411290

+0

텍스트 필드를 전역 변수로 저장할 필요가 없습니다. – rmaddy

+0

나는 self.price = self.tField.text를 추가 중입니다! 내 "완료"처리기 내부. 그것은 내 DB (경보 후)에 저장하려고 할 때 값을 저장하는 것처럼 보이지 않습니다. 나는 이것이 올바른 방향으로가는 것은 아니라고 생각합니다. 정확한 구현을 시도하겠습니다. – user2411290

-1

내 생각 엔 당신이 경고를 제시 할 때 현재의 ViewController는 경고의 ViewController입니다 ... 그리고 당신의 경고에 어떤 변수 TField 객체가 없다는 것입니다.

인용구에서 인용문을 사용하면 tField의 값으로 인쇄 한 후에 경고가 표시됩니다. 그 이유는 거기에서 효과가 있었고 귀하의 경우에는 효과가 없습니다.

관련 문제