UISegmentedControl with Image and Title

后端 未结 6 2232
滥情空心
滥情空心 2020-12-15 13:45

I am using a UISegmentedControl inside a UIToolBar as button. I can\'t use a normal UIButtonBarItem, because I need to set the t

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 14:48

    Swift 5

    For those of us who like to use modern API wherever it is possible:

    extension UIImage {
        static func textEmbeded(image: UIImage,
                               string: String,
                    isImageBeforeText: Bool,
                              segFont: UIFont? = nil) -> UIImage {
            let font = segFont ?? UIFont.systemFont(ofSize: 16)
            let expectedTextSize = (string as NSString).size(withAttributes: [.font: font])
            let width = expectedTextSize.width + image.size.width + 5
            let height = max(expectedTextSize.height, image.size.width)
            let size = CGSize(width: width, height: height)
    
            let renderer = UIGraphicsImageRenderer(size: size)
            return renderer.image { context in
                let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2
                let textOrigin: CGFloat = isImageBeforeText
                    ? image.size.width + 5
                    : 0
                let textPoint: CGPoint = CGPoint.init(x: textOrigin, y: fontTopPosition)
                string.draw(at: textPoint, withAttributes: [.font: font])
                let alignment: CGFloat = isImageBeforeText
                    ? 0
                    : expectedTextSize.width + 5
                let rect = CGRect(x: alignment,
                                  y: (height - image.size.height) / 2,
                              width: image.size.width,
                             height: image.size.height)
                image.draw(in: rect)
            }
        }
    }
    

提交回复
热议问题