Не отображается XIB с правильным макетом [iOS Swift] - PullRequest
0 голосов
/ 30 мая 2018

Я пытаюсь создать настраиваемое представление предупреждений и сталкиваюсь с некоторыми проблемами, связанными с тем фактом, что отображаемое представление обрезает нижнюю половину представления (изображения ниже)

Как это отображается:

How it's being displayed

Желаемый результат:

Desired output

Итак, в принципе, у меня есть XIB с именемCustomAlertView поддерживается классом с тем же именем с init следующим образом:

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

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

private func commonInit() {
    Bundle.main.loadNibNamed("CustomAlertView", owner: self, options: nil)
    contentView.frame = self.bounds
    contentView.translatesAutoresizingMaskIntoConstraints = true
    addSubview(contentView)
    //contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

}

У меня есть другой класс, который отвечает за создание предупреждения, CustomAlert, используя customAlertView.Этот класс CustomAlert создает backgroundView и dialogView (который я пытаюсь добавить к нему свой customAlertView) со следующим кодом:

func initialize(title:String, description:String){
    dialogView.clipsToBounds = true

    backgroundView.frame = frame
    backgroundView.backgroundColor = UIColor.black
    backgroundView.alpha = 0.6
    backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTappedOnBackgroundView)))
    addSubview(backgroundView)

    dialogView.frame.origin = CGPoint(x: 0, y: 0)
    dialogView.frame.size = CGSize(width: frame.width-32, height: frame.height/3)

    dialogView.backgroundColor = UIColor.white
    dialogView.layer.cornerRadius = 6

    let alertView = CustomAlertView.init(frame: self.bounds)
    alertView.titleLabel.text = title
    alertView.descriptionLabel.text = description
    alertView.cancelButton.backgroundColor = UIColor.brown

    dialogView.addSubview(alertView)


    addSubview(dialogView)
}

Я считаю,что я путаю с рамками и границами, но не могу найти решение.

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

EDIT

Код для моей функции .show в CustomAlert

func show(animated:Bool){

    self.backgroundView.alpha = 0
    self.dialogView.center = CGPoint(x: self.center.x, y: self.frame.height + self.dialogView.frame.height/2)
    UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
    if animated {
        UIView.animate(withDuration: 0.33, animations: {
            self.backgroundView.alpha = 0.66
        })
        UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: {
            self.dialogView.center  = self.center
        }, completion: { (completed) in

        })
    }else{
        self.backgroundView.alpha = 0.66
        self.dialogView.center  = self.center
    }
}

Ссылка на Github git-alert-view

Ответы [ 3 ]

0 голосов
/ 11 августа 2018

Для тех, кто сталкивался с теми же трудностями, что и я, я мог достичь желаемого результата.

Я использовал AutoLayouts, как предложено @HAK.Но вместо того, чтобы писать свою собственную NSLayoutConstraint, я использовал библиотеку Робертейна, названную TinyConstraints .

В основном, я использовал следующее:

Вместо

NSLayoutConstraint.activate([
alertView.topAnchor.constraint(equalTo: superview.topAnchor, constant: 0),
alertView.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0),
alertView.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0),
alertView.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: 
0)])

с TinyConstraints:

alertView.edges(to: superview)

Вот и все

0 голосов
/ 11 августа 2018

В вашем классе XIB добавить это:

override func awakeFromNib() {
    super.awakeFromNib()
    xibSetup()}

func xibSetup() {
    guard let view = loadViewFromNib() else { return }
    view.frame = bounds
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    addSubview(view)
    contentView = view
}

Ссылка от этого: https://medium.com/zenchef-tech-and-product/how-to-visualize-reusable-xibs-in-storyboards-using-ibdesignable-c0488c7f525d#.3c0javomy**

0 голосов
/ 30 мая 2018

Измените свой CustomAlertView следующим образом:

class CustomAlertView: UIView {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!

    @IBOutlet weak var confirmButton: UIButton!
    @IBOutlet weak var cancelButton: UIButton!

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    static func customAlert() -> CustomAlertView {
        return Bundle.main.loadNibNamed("CustomAlertView", owner: self, options: nil)!.first as! CustomAlertView
    }

}

Ваш метод инициализации CustomAlert выглядит следующим образом:

func initialize(title:String, description:String){
    dialogView.clipsToBounds = true

    backgroundView.frame = frame
    backgroundView.backgroundColor = UIColor.black
    backgroundView.alpha = 0.6
    backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTappedOnBackgroundView)))
    addSubview(backgroundView)

    dialogView.frame.origin = CGPoint(x: 0, y: 0)
    dialogView.frame.size = CGSize(width: frame.width-32, height: frame.height/3)

    dialogView.backgroundColor = UIColor.white
    dialogView.layer.cornerRadius = 6

    let alertView = CustomAlertView.customAlert()
    alertView.titleLabel.text = title
    alertView.descriptionLabel.text = description
    alertView.cancelButton.backgroundColor = UIColor.brown


    dialogView.addSubview(alertView)

    addSubview(dialogView)

}

В xib CustomAlertView: 1. Выберите владельца файла и удалите класс (по умолчаниюNSObject).2. Выберите владельца файла, а затем удалите все розетки.3. Выберите представление содержимого и присвойте ему class = CustomAlertView.4. Выберите CustomAlertView и выполните все подключения к розетке.

Конечный Xib: enter image description here

И у вас есть рабочее предупреждение: enter image description here

PS: настроить интерфейс соответствующим образом.

...