Подтвердить что ты не робот

Кнопка границы с прозрачным фоном в Swift

Как я могу сделать границу UIButton похожим на изображение ниже (кнопка "Начало работы" ) с прозрачным фоном?

Как мне добиться этого с помощью раскадровки или как это сделать программно?

enter image description here

4b9b3361

Ответ 1

Настройка backgroundColor на clearColor делает кнопку прозрачной.
Попробуйте, например, код ниже. Вы можете настроить и изменить borderAlpha, cornerRadius и цвета по вашему желанию.

let borderAlpha : CGFloat = 0.7
let cornerRadius : CGFloat = 5.0

button.frame = CGRectMake(100, 100, 200, 40)
button.setTitle("Get Started", forState: UIControlState.Normal)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.clearColor()
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
button.layer.cornerRadius = cornerRadius

Ответ 2

с помощью расширения:

extension UIButton
{
 func setUpLayer(sampleButton: UIButton?) {
  sampleButton!.setTitle("GET STARTED", forState: UIControlState.Normal)
  sampleButton?.tintColor =  UIColor.whiteColor()
  sampleButton!.frame = CGRect(x:50, y:500, width:170, height:40)
  sampleButton!.layer.borderWidth = 1.0
  sampleButton!.layer.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.5).CGColor
  sampleButton!.layer.cornerRadius = 5.0

  sampleButton!.layer.shadowRadius =  3.0
  sampleButton!.layer.shadowColor =  UIColor.whiteColor().CGColor
  sampleButton!.layer.shadowOpacity =  0.3
 }

}

Применение:

  let sampleUIButton =  UIButton()
  sampleUIButton.setUpLayer(sampleUIButton)
  self.view.addSubview(sampleUIButton)

Ответ 3

Используя Swift 3, для Storyboard просто добавьте этот подкласс в свой проект, затем в Identity Inspector сделайте это классом для UIButton на вашем раскадровке. Затем вы можете настроить цвет и ширину рамки.

@IBDesignable class CustomButton: UIButton {

 @IBInspectable var borderColor: UIColor = UIColor.white {
    didSet {
        layer.borderColor = borderColor.cgColor
    }
 }

 @IBInspectable var borderWidth: CGFloat = 2.0 {
    didSet {
        layer.borderWidth = borderWidth
    }
 }

 override public func layoutSubviews() {
    super.layoutSubviews()
    clipsToBounds = true
 }
}

Ответ 4

Swift 5

Подобно @rakeshbs, но в Swift 5:

    let borderAlpha : CGFloat = 0.7
    let cornerRadius : CGFloat = 5.0

    self.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
    self.setTitle("Login", for: UIControl.State.normal)
    self.setTitleColor(UIColor.white, for: UIControl.State.normal)
    self.backgroundColor = UIColor.clear
    self.layer.borderWidth = 1.0
    self.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).cgColor
    self.layer.cornerRadius = cornerRadius