【发布时间】:2016-09-30 09:07:55
【问题描述】:
【问题讨论】:
-
按钮使用透明背景图片。
-
为按钮添加一个 CAGradientLayer 并设置其
colors和locations属性。
标签: ios iphone user-interface mobile uibutton
【问题讨论】:
colors 和 locations 属性。
标签: ios iphone user-interface mobile uibutton
您可以使用 CAGradientLayer。虽然结果不完全一样,但比在按钮大小变化时设置背景图片有优势。
下面的代码已经为 Xcode Playground 准备好了:
import UIKit
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 30))
button.setTitle("Order", for: .normal)
button.backgroundColor = UIColor.darkGray
let gradientLayer = CAGradientLayer()
gradientLayer.frame = button.bounds
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) //Set the start point to the left edge center
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) //Set end point to the right edge center
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.red.withAlphaComponent(0.5).cgColor, UIColor.red.withAlphaComponent(0.5).cgColor, UIColor.clear.cgColor]
gradientLayer.locations = [0, 0.2, 0.8, 1] //At the start point, the clear color is used; at 20% horizontal, red is used, etc
button.layer.insertSublayer(gradientLayer, at: 0)
button
【讨论】:
Swift 2.3
对代码的改动很小button.backgroundColor = UIColor.darkGrayColor()
let gradientLayer = CAGradientLayer()
gradientLayer.frame = button.bounds
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) //Set the start point to the left edge center
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) //Set end point to the right edge center
gradientLayer.colors = [UIColor.clearColor().CGColor, UIColor.redColor().colorWithAlphaComponent(0.5).CGColor, UIColor.redColor().colorWithAlphaComponent(0.5).CGColor, UIColor.clearColor().CGColor]
gradientLayer.locations = [0, 0.2, 0.8, 1] //At the start point, the clear color is used; at 20% horizontal, red is used, etc
button.layer.insertSublayer(gradientLayer, atIndex: 0)
【讨论】: