Кнопка не полностью нарисована - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть кнопка с текстом и изображением на нем.Он настраивается в viewDidAppear, а затем в IBAction я меняю заголовок Attributed.По какой-то причине цвет фона кнопки не полностью покрывает кнопку при начальном рисовании.Это оставляет горизонтальную полоску белого цвета.Я обнаружил, что при запуске моей функции formatButton в последующих нажатиях кнопок IBAction отображается правильно нарисованная кнопка.Но я не могу заставить первый загруженный вид кнопки выглядеть правильно.Любые идеи?

Я обнаружил, что, отформатировав в IBAction, он исправил это для будущих отрисовок кнопок, но sendAction (.touchUpInside) даже не смог подделать его для решения проблемы отрисовки.(Он изменил текст кнопки, как это делает IBAction.)

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    formatButton(btn: searchTitlesButton)
    formatButton(btn: searchPeopleButton)
    formatButton(btn: searchCategoryButton)
    searchTitlesButton.setTitle("Title", for: .normal)
    searchPeopleButton.setTitle("Actor", for: .normal)
    //searchCategoryButton.setTitle(categoryList[searchCategoryIndex], for: .normal)

    let fullString = NSMutableAttributedString()
    let imageAttachment = NSTextAttachment()
    imageAttachment.image = UIImage(named:"DownArrow")
    let imageString = NSAttributedString(attachment: imageAttachment)
    fullString.append(NSAttributedString(string: categoryList[searchCategoryIndex]+"   "))
    fullString.append(imageString)
    searchCategoryButton.setAttributedTitle(fullString, for: .normal)

    formatButton(btn: searchCategoryButton)

    postTableView.rowHeight = CGFloat(120)
}

@IBAction func searchCategoryButton(_ sender: Any) {
    if searchCategoryIndex < categoryList.count - 1 {
        searchCategoryIndex += 1
    } else {
        searchCategoryIndex = 0
    }
    // Going to try and make a formatted label with a string and image of a down arrow.
    let fullString = NSMutableAttributedString()
    let imageAttachment = NSTextAttachment()
    imageAttachment.image = UIImage(named:"DownArrow")
    let imageString = NSAttributedString(attachment: imageAttachment)
    fullString.append(NSAttributedString(string: categoryList[searchCategoryIndex]+"   "))
    fullString.append(imageString)
    searchCategoryButton.setAttributedTitle(fullString, for: .normal)
    formatButton(btn: searchCategoryButton)
}

func formatButton(btn:UIButton) {

    btn.layer.cornerRadius = 5
    btn.layer.borderWidth = 1
    btn.layer.borderColor = UIColor.black.cgColor
    btn.setTitleColor(UIColor.white, for: .normal)
    btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = btn.bounds
    let bottomColor = UIColor(red: CGFloat(25/255.0), green: CGFloat(113/255.0), blue: CGFloat(255/255.0), alpha: CGFloat(1.0))
    gradientLayer.colors = [UIColor.white.cgColor, bottomColor.cgColor]
    btn.layer.insertSublayer(gradientLayer, at: 0)
    btn.clipsToBounds = true
}

1 Ответ

1 голос
/ 23 сентября 2019

Причина, по которой градиент фона не полностью покрывает кнопку, возможно, из-за того, что размер кнопки изменяется при установке присвоенного заголовка.Лучший способ решить эту проблему - создать подкласс UIButton, чтобы вы могли обновлять фрейм вашего пользовательского градиентного слоя при каждом изменении границ кнопки.Например:

class GradientButton: UIButton {

    private let gradientLayer = CAGradientLayer()

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

    private func setup() {
        layer.cornerRadius = 5
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
        setTitleColor(UIColor.white, for: .normal)
        titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold)
        let bottomColor = UIColor(red: CGFloat(25/255.0), green: CGFloat(113/255.0), blue: CGFloat(255/255.0), alpha: CGFloat(1.0))
        gradientLayer.colors = [UIColor.white.cgColor, bottomColor.cgColor]
        layer.insertSublayer(gradientLayer, at: 0)
        clipsToBounds = true
    }

    override var bounds: CGRect {
        didSet {
            gradientLayer.frame = layer.bounds
        }
    }
}

Затем в раскадровке пера вы можете изменить класс кнопки на GradientButton.Теперь он должен автоматически применять стиль градиента и обновлять рамку всякий раз, когда изменяются границы кнопки.

Надеюсь, вы найдете это полезным.Дайте мне знать, если у вас все еще есть проблемы.

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