[ios] 음성 및 밑줄

본 포스트에서는 iOS 앱에서 음성 기능과 텍스트에 밑줄을 추가하는 방법에 대해 알아보겠습니다.

음성 기능 추가하기

iOS 앱에 음성 기능을 추가하려면 AVFoundation 프레임워크를 사용하여 음성을 녹음하고 재생할 수 있습니다. 다음은 음성 녹음과 재생을 위한 간단한 예제 코드입니다.

import AVFoundation

class VoiceRecordingViewController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
    var audioRecorder: AVAudioRecorder!
    var audioPlayer: AVAudioPlayer!

    // 음성 녹음
    func startRecording() {
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(.playAndRecord, mode: .default)
            try audioSession.setActive(true)
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]
            audioRecorder = try AVAudioRecorder(url: audioFileURL, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()
        } catch {
            // 오류 처리
        }
    }

    // 음성 재생
    func playRecordedAudio() {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: audioRecorder.url)
            audioPlayer.delegate = self
            audioPlayer.play()
        } catch {
            // 오류 처리
        }
    }
}

이 예제에서는 AVFoundation 프레임워크의 AVAudioRecorderAVAudioPlayer 클래스를 사용하여 음성 녹음과 재생을 수행합니다.

텍스트에 밑줄 추가하기

iOS에서 텍스트에 밑줄을 추가하려면 NSAttributedString을 사용하여 텍스트를 스타일링할 수 있습니다. 아래 예제 코드는 UILabel에 밑줄을 추가하는 방법을 보여줍니다.

let attributedString = NSMutableAttributedString(string: "밑줄이 있는 텍스트")
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: 1, range: NSRange(location: 0, length: attributedString.length))
yourLabel.attributedText = attributedString

이 예제에서는 NSAttributedString을 사용하여 “밑줄이 있는 텍스트”라는 문자열에 밑줄을 추가하고, 그것을 UILabel의 속성 텍스트로 설정하는 방법을 보여줍니다.

이제 음성 녹음 및 재생 기능을 추가하는 방법과 텍스트에 밑줄을 추가하는 방법에 대해 알아보았습니다.