Подкласс UIButton, заполнение SafeArea, вставка содержимого - PullRequest
1 голос
/ 17 мая 2019

Я использую безопасную область при использовании пользовательских элементов пользовательского интерфейса в .xib / .storyboard.

Теперь у меня есть случай, когда у меня есть подкласс UIButton, который используется повсюду в приложении. Так как это просто подкласс (а не пользовательский класс в .xib), я не уверен, как бы я обновил это, чтобы соответствовать моим потребностям.

См. Следующую фотографию: iPhone X button Здесь желтый UIButton. На «обычных» айфонах этот желтый цвет является нижней частью экрана. Я пытаюсь добиться того, чтобы кнопка дошла до нижней части безопасной зоны, оставаясь в том же положении (над безопасной зоной).

Обычно я бы ограничил кнопку superview.bottom, а в .xib кнопки ограничил содержимое (titleLabel, buttonImage и т. Д.) safearea.bottom.

Так как здесь это невозможно, как бы я это сделал?

Я попытался добавить ограничения программно в подклассе UIButton, но безрезультатно.

* * Пример тысяча двадцать-один: * * 1 022
if #available(iOS 11.0, *) {
    NSLayoutConstraint.activate([
        (titleLabel?.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor))!,
        (titleLabel?.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor))!
        ])
} else {
    // Fallback on earlier versions
}

Заранее спасибо!

1 Ответ

1 голос
/ 17 мая 2019

Вы можете использовать для этого следующий подход,

  1. Создать UIView.
  2. Добавьте UILabel к созданному выше view как subView.
  3. Добавьте UIButton к созданному выше view как subView.

Примените правильный layout constraints, чтобы получить желаемый интерфейс.

func addSaveButton() {
    let height: CGFloat = 60 + self.view.safeAreaInsets.bottom //Height based on safe area

    //Custom View
    let customView = UIView(frame: CGRect.init(x: 0, y: self.view.bounds.height - height, width: self.view.bounds.width, height: height))
    customView.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)

    //Save Label
    let label = UILabel()
    label.text = "Save"
    label.textColor = UIColor.black

    //Button
    let button = UIButton(frame: customView.bounds)
    button.addTarget(self, action: #selector(onTapSaveButton), for: .touchUpInside)

    //Add label, button as subview in customView
    customView.addSubview(label)
    customView.addSubview(button)
    self.view.addSubview(customView)

    customView.translatesAutoresizingMaskIntoConstraints = false
    label.translatesAutoresizingMaskIntoConstraints = false
    button.translatesAutoresizingMaskIntoConstraints = false

    //Add constraints
    NSLayoutConstraint.activate([
        self.view.leadingAnchor.constraint(equalTo: customView.leadingAnchor),
        customView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
        customView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        customView.heightAnchor.constraint(equalToConstant: height),

        label.topAnchor.constraint(equalTo: customView.topAnchor, constant: 10),
        label.trailingAnchor.constraint(equalTo: customView.trailingAnchor, constant: -10),

        button.topAnchor.constraint(equalTo: customView.topAnchor),
        button.leadingAnchor.constraint(equalTo: customView.leadingAnchor),
        button.trailingAnchor.constraint(equalTo: customView.trailingAnchor),
        button.bottomAnchor.constraint(equalTo: customView.bottomAnchor)
        ])

}

@objc func onTapSaveButton() {
    print("Save button pressed")
}

В iPhone-X

enter image description here

В iPhone-8

enter image description here

Подход 2:

Вы можете придерживаться более упрощенного подхода, играя с button's titleEdgeInsets.

func addSaveButton() {
    let height: CGFloat = 60 + self.view.safeAreaInsets.bottom

    //Button
    let button = UIButton(frame: CGRect.init(x: 0, y: UIScreen.main.bounds.height - height, width: UIScreen.main.bounds.width, height: height))
    button.setTitle("Save", for: .normal)
    button.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
    button.contentHorizontalAlignment = .right
    button.contentVerticalAlignment = .top
    button.titleEdgeInsets.top = 10
    button.titleEdgeInsets.right = 10
    button.addTarget(self, action: #selector(onTapSaveButton), for: .touchUpInside)

    self.view.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false

    //Add constraints
    NSLayoutConstraint.activate([
        self.view.leadingAnchor.constraint(equalTo: button.leadingAnchor),
        button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
        button.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        button.heightAnchor.constraint(equalToConstant: height)
        ])
}

Вы можете легко сделать то же самое в storyboard/subclassing. Я думаю, что этот лучше, чем предыдущий.

Подход 3:

Подкласс UIButton и используйте его для программного создания кнопки.

class CustomButton: UIButton {
    override func draw(_ rect: CGRect) {
        self.contentHorizontalAlignment = .right
        self.contentVerticalAlignment = .top
        self.titleEdgeInsets.top = 10
        self.titleEdgeInsets.right = 10
    }
}
...