首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有可能做一个这样的UITextField吗?

有可能做一个这样的UITextField吗?
EN

Stack Overflow用户
提问于 2019-07-11 02:12:09
回答 1查看 148关注 0票数 1

情景:我想在一个xcode项目中为我的textField使用一个自定义的UITextField类。我想让textField看起来像这样:

我没有问题,使边缘变圆,并改变我的占位符的颜色,但我不知道如何保持底部边缘平坦,并只在底部绘制一个黑色边框。

这是我的代码:

代码语言:javascript
复制
import UIKit

class GrayTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .grayf1f1f1
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
        layer.cornerRadius = 10
        clipsToBounds = true
    }

    override var placeholder: String? {
        didSet {
            let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .thin)]
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
        }
    }
}

我现在的结果是:

EN

回答 1

Stack Overflow用户

发布于 2019-07-11 03:21:41

嗯,经过一些研究之后,我就这么做了。下面是我的最终代码:

代码语言:javascript
复制
import UIKit

class GrayTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .grayf1f1f1
        clipsToBounds = true

        let maskPath = UIBezierPath(roundedRect: self.bounds,
                                    byRoundingCorners: [.topLeft, .topRight],
                                    cornerRadii: CGSize(width: 10.0, height: 10.0))

        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape

        addBottomBorder(with: .darkGray, andWidth: 1)
    }


    override var placeholder: String? {
        didSet {
            let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .thin)]
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
        }
    }

    func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
        let border = UIView()
        border.backgroundColor = color
        border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
        border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
        addSubview(border)
    }
}

这就是结果:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56976419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档