Swift结合代码

时间:2018-02-23 16:22:48

标签: swift

我正在使用Xcode / Swift编写应用程序。我想将这两个代码函数组合成一个较小的代码函数,以消除重复的代码。

第一部分代码:

@IBAction func StopRecording(_ sender: Any) {
     recordButton.isEnabled = true
     stopRecordingButton.isEnabled = false
     recordingLabel.text = "Tap to record"
     audioRecorder.stop()
     let audioSession = AVAudioSession.sharedInstance()
     try! audioSession.setActive(false)
}

代码的第二部分:

@IBAction func recordAudio(_ sender: AnyObject) {
    recordingLabel.text = "Recording in progress"
    stopRecordingButton.isEnabled = true
    recordButton.isEnabled = false

这是我的不良尝试:

@IBAction func recordAudio(_ sender: AnyObject) {
        func SetLabel(recordButton: Bool, recordingText:String)
        if recordButton = true
            recordingLabel.text = "Recording in progress"
            stopRecordingButton.isEnabled = true
            recordButton.isEnabled = false
    else if {
        @IBAction func StopRecording(_ sender: Any) {
            recordButton.isEnabled = true
            stopRecordingButton.isEnabled = false
            recordingLabel.text = "Tap to record"
            audioRecorder.stop()
            let audioSession = AVAudioSession.sharedInstance()
            try! audioSession.setActive(false)
        }
                }

    {

1 个答案:

答案 0 :(得分:2)

试试这个:

func updateButtons(recording: Bool) {
    recordingLabel.text = recording ? "Recording in progress" : "Tap to record"
    stopRecordingButton.isEnabled = recording
    recordButton.isEnabled = !recording
}