UISegmentedControl更改ONE段的字体

时间:2017-05-09 13:36:23

标签: ios swift swift3 uisegmentedcontrol uifont

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

我知道如何为整个控件做到这一点。但是如果用户有某些内容,我想强调一个细分。但是这个没有被选中。

注意:我使用的是swift 3

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,所以评论是正确的。我需要一个该段的图像。我拼凑了一些答案来得到这个:

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

谢谢!