Незначительное изменение вашего кода, и это сработало для меня.
Для тех, кто сталкивается с той же проблемой, предложение:
- Определите класс ответчика.
- напишите действие, которое вы хотите связать с кнопкой внутри этого класса
- определить экземпляр Responser
- addTarget к экземпляру и связать действие
Пример кода
import PlaygroundSupport
import UIKit
//
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.909803926944733, green: 0.47843137383461, blue: 0.643137276172638, alpha: 1.0)
view.frame = CGRect(x: 0, y: 0, width: 400, height: 300)
let lbl = UILabel(frame: CGRect(x: 50, y: 0, width: 200, height: 50))
lbl.text = "Hello, World!"
view.addSubview(lbl)
let txt = UITextField(frame: CGRect(x: 150, y: 200, width: 200, height: 50))
txt.placeholder = "Enter text here"
//txt.font = UIFont.systemFont(ofSize: 15)
txt.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
txt.borderStyle = UITextBorderStyle.roundedRect
view.addSubview(txt)
let button = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 50))
button.backgroundColor = #colorLiteral(red: 0.721568644046783, green: 0.886274516582489, blue: 0.592156887054443, alpha: 1.0)
//button.setTitleColor(#colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0), for: UIControlState.selected)
button.setTitle("button", for: UIControlState.selected)
button.layer.cornerRadius = 10
view.addSubview(button)
class Responser: NSObject
{
//Method to be called
func printname()
{
print ("clicked")
lbl.text = "aha"
}
}
let responder = Responser()
button.addTarget(responder, action: #selector(Responser.printname), for:.touchUpInside)
PlaygroundPage.current.liveView = view
person
XueYu
schedule
17.04.2017