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

Я создаю пользовательскую кнопку, код которой приведен ниже. Все элементы оформления работают, однако мои подпредставления имя и изображение не добавляются. Я уверен, что это простая ошибка, но я был бы признателен, если бы кто-то мог мне помочь. Спасибо.

class MaterialButton: UIButton {

    let name = UILabel()
    let image = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupButton()
    }

    func setupButton() {
        name.textColor = .white
        //        name.font = UIFont(name: "HelveticaNeue-UltraLight",size: 10.0)
        name.textAlignment = .center
        self.layer.cornerRadius = 20
        addSubview(name)
        positionName()

        addSubview(image)
        positionImage()
    }

    func positionName() {
        name.translatesAutoresizingMaskIntoConstraints = false
        name.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 10).isActive = true
        name.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
        name.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
        name.heightAnchor.constraint(equalToConstant: self.bounds.height - image.bounds.height - 20).isActive = true
    }
    func positionImage() {
        image.translatesAutoresizingMaskIntoConstraints = false
        image.heightAnchor.constraint(equalToConstant: image.bounds.width).isActive = true
        image.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
        image.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
        image.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
    }
}

Пример реализации кнопки (другая кнопка была объявлена ​​инициализированной ранее с помощью кнопки материала в коде)

func setupOtherButton() { // Setting up plastic button
        otherButton.name.text = "Other"
        otherButton.name.textColor = .white
        otherButton.backgroundColor = .gray
        miniSV1.addSubview(otherButton) // Add plastic button to view
        otherButton.addTarget(self, action: #selector(otherButtonTapped), for: .touchUpInside)
    }

1 Ответ

0 голосов
/ 08 марта 2020

Ну, я не знаю точный пользовательский интерфейс, который вы реализуете, но я внес некоторые изменения в ваш код и получил следующий пользовательский интерфейс:

enter image description here

Поэтому для кнопки в viewDidLoad:

class ViewController: UIViewController {

    var otherButton = MaterialButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        otherButton.frame = CGRect(x: 10, y: 180, width: 140, height: 140)
        otherButton.name.text = "Other"
        otherButton.name.textColor = .white
        otherButton.backgroundColor = .gray
        self.view.addSubview(otherButton)
    }
}

И несколько изменений в ограничениях:

class MaterialButton: UIButton {

    let name = UILabel()
    let image = UIImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupButton()
    }

    func setupButton() {
        image.backgroundColor = UIColor.yellow
        addSubview(image)
        positionImage()

        name.textColor = .white
        name.textAlignment = .center
        name.backgroundColor = .blue
        self.layer.cornerRadius = 20
        addSubview(name)
        positionName()
    }

    func positionName() {
        name.translatesAutoresizingMaskIntoConstraints = false
        name.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true
        name.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
        name.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
        name.heightAnchor.constraint(equalToConstant: 20).isActive = true
    }

    func positionImage() {
        image.translatesAutoresizingMaskIntoConstraints = false
        image.heightAnchor.constraint(equalToConstant: 50).isActive = true
        image.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
        image.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
        image.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
    }
}

Проверьте этот URL для лучшего понимания ограничений программно:

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