Я создал простую структуру для своего пользовательского представления. С моей точки зрения, я хочу, чтобы его можно было многократно использовать в нескольких приложениях. Проблема в том, что когда я меняю ограничения в проекте, представление не реагирует на какие-либо действия, такие как нажатие кнопки, при вводе текста в textField. Я предполагаю, что проблемы кроются в translatesAutoresizingMaskIntoConstraints
.
Предположим, что у меня есть структура, подобная приведенной ниже:
public class CustomView: UIView {
public let customButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Save", for: .normal)
button.layer.cornerRadius = 10
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.red.cgColor
button.setTitleColor(.red, for: .normal)
return button
}()
public var buttonWidth: CGFloat = 100
public override init(frame: CGRect) {
super.init(frame: frame)
initConstraints()
}
func initConstraints(){
addSubview(customButton)
NSLayoutConstraint.activate([
customButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 80),
customButton.centerXAnchor.constraint(equalTo: centerXAnchor),
customButton.widthAnchor.constraint(equalToConstant: buttonWidth)
])
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}}
После успешного добавления структуры в проект мне нужно изменить положение обзора. Из центра, чтобы быть выше. Я создаю класс
class FrameworkView: UIView {
let customButton: CustomView = {
let cusomView = CustomView()
cusomView.translatesAutoresizingMaskIntoConstraints = false
return cusomView
}()
override init(frame: CGRect) {
super.init(frame: frame)
initConst()
}
func initConst() {
addSubview(customButton)
NSLayoutConstraint.activate([
customButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 100),
customButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25),
customButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -25),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}}
Все выглядит нормально, когда я добавляю представление в ViewController.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let demo = FrameworkView(frame: view.frame)
view.addSubview(demo)
demo.customButton.customButton.addTarget(self, action: #selector(tap(_:)), for: .touchUpInside)
}
@objc func tap(_ sender: UIButton){
print("Test")
}
К сожалению, кнопка не реагирует на действие. То же самое и с другими представлениями, такими как textFields, TextViews и т. Д. c. Я не могу понять, как решить эту ошибку. Я предполагаю, что что-то не так с подпредставлениями и ограничениями. Спасибо за любую помощь. Мэтт