如何为MDCTextField添加阴影?

时间:2019-02-17 13:22:11

标签: ios swift xcode mdc-components

这是我的代码:

@IBOutlet var txtFirstName: MDCTextField!
var txtFirstNameController: MDCTextInputControllerOutlined?
override func viewDidLoad() {
txtFirstNameController = MDCTextInputControllerOutlined(textInput: txtFirstName)
}

我想在文本字段中添加阴影,但是我不知道如何使用MaterialComponents 我在这里提到了我测试过的所有方法及其结果:

第一种方式:

class ShadowLayer : MDCTextField{
override class var layerClass: AnyClass {
    return MDCShadowLayer.self
}

var shadowLayer: MDCShadowLayer {
    return self.layer as! MDCShadowLayer
}

func setDefaultElevation() {
    self.shadowLayer.elevation = .cardResting
}
}

第二种方式:

extension MDCTextField {

func elevate(elevation: Double) {
    self.backgroundColor = UIColor.white
    self.layer.masksToBounds = false
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOffset = CGSize(width: 0, height: elevation)
    self.layer.shadowRadius = CGFloat(elevation)
    self.layer.shadowOpacity = 1

}
}

choose country -> 1st way, choose city-> 2nd way

选择国家->第一种方式,选择城市->第二种方式

我想要的是下图:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试设置self.clipsToBounds = true 之前设置self.layer.masksToBounds = false

您的提升功能应如下所示:

func elevate(elevation: Double) {
    self.backgroundColor = UIColor.white
    self.clipsToBounds = true
    self.layer.masksToBounds = false
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOffset = CGSize(width: 0, height: elevation)
    self.layer.shadowRadius = CGFloat(elevation)
    self.layer.shadowOpacity = 1
}