【问题标题】:UISegmentedControl Corner Radius Not ChangingUISegmentedControl 角半径不变
【发布时间】:2020-08-25 18:54:29
【问题描述】:

UISegmentedControl 圆角半径没有改变。我还在this 问题中关注了一些答案,我的 UISegmentedControl 的角半径仍然没有改变。我跟着This tutorial 创建了 UISegmentedControl。

代码:


import UIKit

class SegmentViewController: UIViewController {

    private let items = ["Black", "Red", "Green"]
    lazy var segmentedConrol: UISegmentedControl = {
        let control = UISegmentedControl(items: items)
        
        return control
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupViews()
    }
    fileprivate func setupViews(){
        view.addSubview(segmentedConrol)
        
        segmentedConrol.translatesAutoresizingMaskIntoConstraints = false //set this for Auto Layout to work!
        segmentedConrol.heightAnchor.constraint(equalToConstant: 40).isActive = true
        segmentedConrol.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
        segmentedConrol.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
        segmentedConrol.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        segmentedConrol.selectedSegmentIndex = 1
        //style
        segmentedConrol.layer.cornerRadius = 20
        segmentedConrol.layer.borderWidth = 2
        segmentedConrol.layer.borderColor = UIColor.black.cgColor
        segmentedConrol.backgroundColor = .red
        segmentedConrol.selectedSegmentTintColor = .darkGray
//        segmentedConrol.clipsToBounds = true
        segmentedConrol.layer.masksToBounds = true
    }

}

(PS。对于大多数人来说答案可能很简单,请不要介意我,我是这个领域的新手。)

【问题讨论】:

  • 好消息,坏消息。你没有做一些简单的事情——它看起来(对我来说)好像cornerRadius 没有为UISegmentedControl 做任何事情。 (顺便说一句,你的代码对我来说看起来不错。)回到过去(我已经半退休)我会回答这样的问题:“你能给我一个你想要的工作示例吗?”如果没有创建自己的分段控件,您可能会被困在这里。
  • 您好,我会尽我所能,更清楚地展示我想要的东西。和平。

标签: ios swift ios13 uisegmentedcontrol


【解决方案1】:

子类UISegmentedControl 并覆盖layoutSubviews。在方法内部将圆角半径设置为您想要的值,您可以删除setupViews()中设置圆角半径的部分:

class YourSegmentedControl: UISegmentedControl {
    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = 20
    }
}

在您创建segmentedControl 的视图控制器中,创建YourSegmentedControl 的实例,如下所示。

lazy var segmentedConrol: YourSegmentedControl = {
            let control = YourSegmentedControl(items: items)

            return control
        }()

结果是:

【讨论】:

  • 您好,感谢您的回复。你知道为什么它只能通过覆盖函数来工作吗?我真的很好奇为什么在教程中我遵循它工作正常但在我的代码/Xcode 中却没有?
  • 我相信 UISegmentedControl 在 iOS 13 中收到了很大的更新,现在控件绘制了默认角半径为 15 的矩形。根据我的阅读,您无权更改创建后的角落。如果您将构建目标降到 iOS 12 并在运行 iOS 12 的设备上运行它,我相信您所拥有的会起作用。
猜你喜欢
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
相关资源
最近更新 更多