Как сделать кнопку градиента в нижнем колонтитуле UICollectionView в Swift? - PullRequest
0 голосов
/ 10 июня 2019

Я столкнулся с проблемой.Я делаю приложение, в котором мне нужно сделать кнопку с градиентным цветом внутри нижнего колонтитула UICollectionView , и проблема в том, что я не могу сделать это через раскадровку, поэтому я должен сделать это программно в пределахнижний колонтитул UICollectionView .Но я не знаю, как это сделать.

Дело в том, что я пытался сделать это, я выполнил, чтобы сделать базовую структуру UIButton внутри UICollectionView 's Нижний колонтитул.

case UICollectionView.elementKindSectionFooter:

    let footer = outerMainCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath) as! headerReusableView

    let button = UIButton(frame: CGRect(x: 0, y: 0, width: collectionView.frame.width - 50, height: 40))

    if isGuest {
        button.backgroundColor = .red
    } else {
        button.backgroundColor = .black
    }

    button.setTitle("ALL", for: .normal)
    button.setTitleColor(COLORWHITE, for: .normal)
    button.addTarget(self, action: #selector(footerButton), for: .touchUpInside)

    footer.addSubview(button)

    footer.backgroundColor = UIColor.green

    return footer

Я хочу сделать градиент между светлым оранжевым и темно-оранжевым, например, использовать любые шестнадцатеричные значения, и я хочу, чтобы его высота по центру составляла 40, а поля были со всех сторон.- сверху, снизу, слева, справа.

Ответы [ 2 ]

1 голос
/ 10 июня 2019

Представление «Коллекция» предоставляет возможность добавить нижний колонтитул, используя Xib и раскадровку, но, тем не менее, если вы хотите добавить ограничения программно, вы можете использовать следующую функцию

func addSubviewInSuperview(subview : UIView , andSuperview superview : UIView) {

    subview.translatesAutoresizingMaskIntoConstraints = false;

    let leadingConstraint = NSLayoutConstraint(item: subview,
                                               attribute: .leading,
                                               relatedBy: .equal,
                                               toItem: superview,
                                               attribute: .leading,
                                               multiplier: 1.0,
                                               constant: 0)

    let trailingConstraint = NSLayoutConstraint(item: subview,
                                                attribute: .trailing,
                                                relatedBy: .equal,
                                                toItem: superview,
                                                attribute: .trailing,
                                                multiplier: 1.0,
                                                constant: 0)

    let topConstraint = NSLayoutConstraint(item: subview,
                                           attribute: .top,
                                           relatedBy: .equal,
                                           toItem: superview,
                                           attribute: .top,
                                           multiplier: 1.0,
                                           constant: 0)

    let bottomConstraint = NSLayoutConstraint(item: subview,
                                              attribute: .bottom,
                                              relatedBy: .equal,
                                              toItem: superview,
                                              attribute: .bottom,
                                              multiplier: 1.0,
                                              constant: 0.0)

    superview.addSubview(subview)
    superview.addConstraints([leadingConstraint,trailingConstraint,topConstraint,bottomConstraint])
}  

Чтобы установить градиент на фон кнопки: -

func setGradient() {
    let color1 =  UIColor.red.cgColor
    let color2 = UIColor.blue.cgColor

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [color1, color2]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.frame = self.view.bounds

    self.btn.layer.insertSublayer(gradientLayer, at:0)
}
0 голосов
/ 10 июня 2019

У меня есть расширение, которое поможет вам добавить цвет градиента в UIButton и UIView.

Расширение

extension UIView {
    func applyGradient(colours: [UIColor]) -> Void {
        self.applyGradient(colours, locations: nil)
    }

    func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.CGColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, atIndex: 0)
    }
}

Вы можете использовать extensionкак ниже.Обязательно объявите свойство кнопки глобальным в ViewController, как показано в примере ниже.

class ViewController: UIViewController {

    @IBOutlet weak var yourButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.yourButton.applyGradient([UIColor.yellowColor(), UIColor.blueColor()])
    }
}
...