【问题标题】:How to make UI of Button like This in iOS?如何在 iOS 中制作这样的按钮 UI?
【发布时间】:2016-09-30 09:07:55
【问题描述】:

我想把这个按钮的ui做成这样,它会支持所有的iphone和ipad屏幕

【问题讨论】:

  • 按钮使用透明背景图片。
  • 为按钮添加一个 CAGradientLayer 并设置其 colorslocations 属性。

标签: ios iphone user-interface mobile uibutton


【解决方案1】:

您可以使用 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

【讨论】:

  • 谢谢......我做了一点改变,然后它会为我工作
【解决方案2】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2021-08-22
    • 2018-11-09
    • 2020-05-27
    • 2012-05-31
    • 1970-01-01
    相关资源
    最近更新 更多