如何在UIButton上的gradientLayer前面设置图像和文本?

时间:2015-05-19 22:18:52

标签: ios swift uibutton layer

我的代码如下所示:

    pickerCountry = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    pickerCountry.frame = CGRectMake(self.view.frame.size.width/2 - pickerCountry.frame.size.width, 50, 100, 100)
    pickerCountry.center.x = self.view.center.x
    pickerCountry.setTitle("Start1", forState: UIControlState.Normal)
    pickerCountry.setImage(UIImage(named: "Britain_mdpi.png"), forState: UIControlState.Normal)
    pickerCountry.tintColor = UIColor.blackColor()
    pickerCountry.titleLabel?.tintColor = UIColor.blackColor()
    pickerCountry.layer.cornerRadius = 2

    pickerCountry.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 200)
    pickerCountry.titleEdgeInsets = UIEdgeInsets(top: 5, left: 50, bottom: 5, right: 5)

    pickerCountry.addTarget(self, action: "countryPicker:", forControlEvents: UIControlEvents.TouchUpInside)
    ContentView.addSubview(pickerCountry)

我在func添加渐变,如下所示:

    let colorTop = UIColor(netHex:0xffffff).CGColor
    let colorBottom = UIColor(netHex:0xebebeb).CGColor

    pickerCountryGradientLayer.masksToBounds = true
    pickerCountryGradientLayer.cornerRadius = pickerCountry.layer.cornerRadius
    pickerCountryGradientLayer.colors = [ colorTop, colorBottom]
    pickerCountryGradientLayer.locations = [ 0.0, 1.0]

    pickerCountry.layer.insertSublayer(pickerCountryGradientLayer, below: pickerCountry.imageView?.layer)

当我使用这最后一行时,insertSublayer就像这样我看到了图像,我看到了标题,但它的颜色是白色,或者某种东西,有点奇怪。我将颜色设置为黑色,所以如果这确实有效,我该如何更改标题颜色?

我尝试使用addSublayer,但后来我看到了标题标签,而不是图片。

1 个答案:

答案 0 :(得分:1)

你提到你设置了UIButton的标题颜色,但我不知道你在哪里设置了UIButton' s标题颜色。使用:

pickerCountry.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)