我想使用相同的UIView类来录制和播放声音。在这个视图类中,我以编程方式添加一个按钮,我想根据视图的目的更改按钮文本。当视图创建为播放器时,它将显示播放图标(或现在的文本)。如果视图创建为记录器,它将显示记录图标。但我无法从我的UIButton视图中访问全局变量。
class AudioPlayerView: UIView {
var isRecorder = false
override init(frame: CGRect) {
super.init(frame: frame)
...
}
let theButton: UIButton = {
let button = UIButton()
if isRecorder {
button.setTitle("▷", for: .normal)
button.addTarget(self, action: #selector(playPauseAudio), for: .touchUpInside)
} else {
button.setTitle("▢", for: .normal)
button.addTarget(self, action: #selector(recordTapped), for: .touchUpInside)
}
button.backgroundColor = .clear
button.layer.cornerRadius = 15.0
return button
}()
答案 0 :(得分:1)
我重新实现了你的播放器课程。现在,您无需为录制和播放状态创建两个单独的视图。您只需更改isRecorder
值即可更改按钮标题,而无需创建其他视图。
class AudioPlayerView: UIView {
var isRecorder = false {
didSet {
if isRecorder {
theButton.setTitle("▷", for: .normal)
} else {
theButton.setTitle("▢", for: .normal)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
if isRecorder {
theButton.setTitle("▷", for: .normal)
} else {
theButton.setTitle("▢", for: .normal)
}
//Add your button to view as subview.
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
let theButton: UIButton = {
let button = UIButton()
button.backgroundColor = .clear
button.layer.cornerRadius = 15.0
button.addTarget(self, action: #selector(tapButton), for: .touchUpInside)
return button
}()
func tapButton() {
if isRecorder {
playPauseAudio()
} else {
recordTapped()
}
}
func playPauseAudio() {
}
func recordTapped() {
}
}
答案 1 :(得分:0)
如果要为每个AudioPlayerView
设置属性,则在属性声明中包含该属性是有意义的。
要做的唯一更改是使按钮成为计算属性以访问self上的属性:
var theButton: UIButton {
let button = UIButton()
if isRecorder {
button.setTitle("▷", for: .normal)
button.addTarget(self, action: #selector(playPauseAudio), for: .touchUpInside)
} else {
button.setTitle("▢", for: .normal)
button.addTarget(self, action: #selector(recordTapped), for: .touchUpInside)
}
button.backgroundColor = .clear
button.layer.cornerRadius = 15.0
return button
}
答案 2 :(得分:0)
实际上,在创建视图后,我在viewcontroller类中进行了跟踪。我只需设置按钮子视图标题并添加相关目标。现在它似乎正在发挥作用。但作为一个新手,我不确定这是否是一个很好的解决方案...感谢每一位分享他们的评论和代码的人。
let doggy: Dog = Dog.create()