【问题标题】:UISegmentedControl change the font of ONE segmentUISegmentedControl 改变一个段的字体
【发布时间】:2017-05-10 02:07:17
【问题描述】:

如何更改 UISegmentedControl 中 ONE 段的字体?

我知道如何为整个控件执行此操作。但是,如果用户在那里有东西,我想突出显示一个部分。但是这个没有被选中。

注意:我使用的是 swift 3

谢谢!

【问题讨论】:

  • 您必须构建自己的界面。这不是 SegmentedControl 的工作方式。
  • 你可以继承 UISegementedControl 并添加任何你喜欢的自定义。
  • 在这种情况下您可能需要使用图像进行分段
  • 是的,我同意,这就是我现在正在尝试的。有代码我会放上去的。

标签: ios swift swift3 uisegmentedcontrol uifont


【解决方案1】:

好的,所以 cmets 是对的。我需要该部分的图像。我拼凑了一些答案来得到这个:

DispatchQueue.main.async(execute: {

        //custom funct to determine the index / just use your index
        guard let segIndexL = self.navMode?.determineIndexForMode(navType: navType) else {

            return
        }


        let width: CGFloat  =  29.0               
        let height: CGFloat = 24.0 //height (28) minus 2pt border for top and bottom
        let size = CGSize(width: width, height: height)


        UIGraphicsBeginImageContextWithOptions(size, false, 0)

        var fontSize: CGFloat? = nil

        for segment in self.segSubViewNavControl.subviews {
            for label in segment.subviews {
                if label is UILabel {
                    fontSize = (label as! UILabel).font.pointSize + 1.0;
                    break
                }

                if fontSize != nil {
                    break
                }
            }   
        }

        guard let fontSizeL = fontSize else {
            return
        }

        let font  = UIFont.boldSystemFont(ofSize: fontSizeL)

        let txtAttributes = [
            NSFontAttributeName : font,
            NSForegroundColorAttributeName : UIColor.red
        ] as [String : Any]

        guard let titleL = self.segSubViewNavControl.titleForSegment(at: segIndexL) else {
            return
        }

        let stringSizeL = titleL.size(attributes: txtAttributes)

        let rectText = CGRect(x: (width - stringSizeL.width) / 2, y: (height - stringSizeL.height) / 2, width: stringSizeL.width, height: stringSizeL.height)


        titleL.draw(
            in: rectText,
            withAttributes: txtAttributes
        )

        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        self.segSubViewNavControl.setImage(newImage, forSegmentAt: segIndexL)


    })

我从这里得到了这些答案:

iOS Drawing text in the centre of shapes

How to make text appear in centre of the image?

How to Create a CGSize in Swift?

How do I add text to an image in iOS Swift

Using isKindOf in Swift 3

谢谢!

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 2013-12-06
    • 1970-01-01
    • 2011-01-17
    • 2012-02-20
    • 2012-01-15
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多