自定义分段控制宽度代码无法正常工作

时间:2016-10-19 00:03:27

标签: ios iphone swift

以下是自定义分段控件的代码,我可以在其中设置外观:

/*
     Init SMsegmentView
     Set divider colour and width here if there is a need
     */
    let segmentFrame = CGRect(x: self.margin, y: 64.0, width: self.view.frame.size.width - self.margin*1, height: 50.0)
    self.segmentView = SMSegmentView(frame: segmentFrame, dividerColour: UIColor(white: 0.95, alpha: 0.3), dividerWidth: 1.0, segmentAppearance: appearance)
    self.segmentView.backgroundColor = UIColor.clear

    self.segmentView.layer.cornerRadius = 0.0
    self.segmentView.layer.borderColor = UIColor(white: 0.85, alpha: 1.0).cgColor
    self.segmentView.layer.borderWidth = 1.0

    // Add segments
    self.segmentView.addSegmentWithTitle("Name", onSelectionImage: UIImage(named: "clip_light"), offSelectionImage: UIImage(named: "clip"))
    self.segmentView.addSegmentWithTitle("Price", onSelectionImage: UIImage(named: "bulb_light"), offSelectionImage: UIImage(named: "bulb"))
    self.segmentView.addSegmentWithTitle("Subject", onSelectionImage: UIImage(named: "cloud_light"), offSelectionImage: UIImage(named: "cloud"))

    self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)), for: .valueChanged)

    // Set segment with index 0 as selected by default
    self.segmentView.selectedSegmentIndex = 0
o   self.view.addSubview(self.segmentView)

唯一的问题是只有分段控制的右侧触摸屏幕的左侧,右侧没有。知道为什么会这样吗?如果需要,我可以提供更多代码。

以下是控件执行操作的视图:SegmentedControl

1 个答案:

答案 0 :(得分:1)

你需要两个边距,一个在右边,一个在左边,所以宽度应该是

let width = self.view.frame.size.width - self.margin*2
let segmentFrame = CGRect(x: self.margin, y: 64.0, width: width, height: 50.0)