Представления не реагируют на действие при добавлении из фреймворка - PullRequest
0 голосов
/ 12 июля 2020

Я создал простую структуру для своего пользовательского представления. С моей точки зрения, я хочу, чтобы его можно было многократно использовать в нескольких приложениях. Проблема в том, что когда я меняю ограничения в проекте, представление не реагирует на какие-либо действия, такие как нажатие кнопки, при вводе текста в 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. Я не могу понять, как решить эту ошибку. Я предполагаю, что что-то не так с подпредставлениями и ограничениями. Спасибо за любую помощь. Мэтт

1 Ответ

1 голос
/ 12 июля 2020

Высота CustomView (той, которая является подвидом FrameworkView) неоднозначна. Это приводит к тому, что он не отображается. Но поскольку кадр UIButton неоднозначен, он все равно отображается. Я думаю, что, возможно, именно поэтому события щелчка не go до кнопки - кадр супервизора кнопки, CustomView неоднозначен.

Причина неоднозначности высоты в том, что вам кажется чтобы забыть нижнее ограничение:

// in FrameworkView
NSLayoutConstraint.activate([
    customButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 100),
    customButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25),
    customButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -25),
    // your forgot this!
    customButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -100)
])

Если вы добавите нижнее ограничение, кнопка будет работать.


Вместо создания другого представления, которое обертывает CustomView, вы можете рассмотрите возможность изменения CustomView, чтобы он отображал свойство topConstraint (поскольку все, что вам кажется, нужно сделать, это немного переместить кнопку вниз):

public class CustomView: UIView {

    public var topConstraint: NSLayoutConstraint!

    ...

    private func initConstraints(){
        addSubview(customButton)
        topConstraint = customButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 80)
        NSLayoutConstraint.activate([
            
            topConstraint,
            customButton.centerXAnchor.constraint(equalTo: centerXAnchor),
            customButton.widthAnchor.constraint(equalToConstant: buttonWidth)

        ])
    }

Теперь вам не нужно FrameworkView, можно установить topConstraint.constant для перемещения кнопки вниз.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...