简体   繁体   English

在Xcode8上自定义UISegmentedControl边框和背景-Swift 3

[英]Customizing UISegmentedControl border and Background on Xcode8 - Swift 3

I'm trying to customize the UISegmented Control's appearance as the follow image: 我正在尝试自定义UISegmented控件的外观,如下图: 在此处输入图片说明

Being more specifically, I'm having problems trying to drop this shadow, setting the height and also the background color. 更具体地说,我在尝试放置阴影,设置高度以及背景颜色时遇到问题。

Can you help me please? 你能帮我吗?

You can customise UISegmentController by sub classing it. 您可以通过子类化自定义UISegmentController。 Please see below code. 请参见下面的代码。

class SegmentController : UISegmentedControl {

 override func awakeFromNib() {
    self.layer.borderWidth = 0
    self.tintColor = UIColor.clear
    self.backgroundColor = UIColor.white
    let segAttributesSelected: NSDictionary = [
        NSAttributedStringKey.foregroundColor: UIColor.red,
        NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 15)
    ]
    let segAttributes: NSDictionary = [
        NSAttributedStringKey.foregroundColor: UIColor.lightGray,
        NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 15)
    ]
    self.setTitleTextAttributes(segAttributesSelected as [NSObject : AnyObject], for: UIControlState.selected)
    self.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.normal)
 }

 override func draw(_ rect: CGRect) {
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowRadius = 2.0
    self.layer.shadowOffset = CGSize.init(width: 0, height: 0)
    self.layer.shadowOpacity = 1.0
    self.layer.backgroundColor = UIColor.white.cgColor
 }
}

Make suitable adjustment to constrains in storyboard to set height and position. 对情节提要中的约束进行适当的调整以设置高度和位置。 故事板屏幕短


Final output 最终输出

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM