You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Charts饼图添加子视图方法及自定义视图嵌入可行性咨询

iOS Charts Library: Adding Subviews & Embedding Custom Center Views

Hey there! Let’s break down your two questions about using the Charts library on iOS—both are totally doable, so let’s dive in.

1. Adding Subviews to a PieChartView

First off, since PieChartView is a subclass of UIView, you can add any subview to it just like you would with a regular UIView. The key is handling layout correctly, especially if you want the subview tied to specific pie slices or to adapt across screen sizes.

Basic Subview Addition (Fixed Position)

If you just need a static subview (like a button or legend), use Auto Layout to pin it relative to the pie chart’s bounds:

// Setup your pie chart first
let pieChart = PieChartView(frame: view.bounds)
view.addSubview(pieChart)
pieChart.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    pieChart.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
    pieChart.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
    pieChart.topAnchor.constraint(equalTo: view.topAnchor, constant: 40),
    pieChart.heightAnchor.constraint(equalTo: pieChart.widthAnchor) // Square pie chart
])

// Add a custom button as a subview
let infoButton = UIButton(type: .infoLight)
infoButton.translatesAutoresizingMaskIntoConstraints = false
pieChart.addSubview(infoButton)

// Pin to top-right corner
NSLayoutConstraint.activate([
    infoButton.trailingAnchor.constraint(equalTo: pieChart.trailingAnchor, constant: -10),
    infoButton.topAnchor.constraint(equalTo: pieChart.topAnchor, constant: 10)
])

Tying Subviews to Pie Slices

If you want a subview to sit on top of a specific slice, use the chart’s built-in method to get the slice’s center position:

// Assuming you have a populated PieChartData instance
if let firstEntry = pieChart.data?.dataSets.first?.entries.first as? PieChartDataEntry {
    // Get the center point of the slice in the chart's coordinate system
    let sliceCenter = pieChart.entryCenter(entry: firstEntry)
    
    // Create a badge view
    let badge = UIView(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
    badge.backgroundColor = .red
    badge.layer.cornerRadius = 12
    pieChart.addSubview(badge)
    
    // Position the badge at the slice's center
    badge.center = sliceCenter
}

2. Embedding a Custom View in the Pie Chart’s Center (Instead of Text)

You’re right that the default centerText property only supports strings, but replacing it with a custom view is straightforward. The easiest way is to add your custom view directly to the PieChartView and constrain it to the center with Auto Layout for screen adaptation.

Step 1: Create Your Custom Center View

First, build the view you want to embed—here’s an example with an image and label:

class PieCenterView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = .white
        layer.cornerRadius = frame.width / 2
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.1
        layer.shadowOffset = CGSize(width: 0, height: 2)
        
        // Add image
        let icon = UIImageView(image: UIImage(systemName: "dollarsign.circle.fill"))
        icon.tintColor = .systemGreen
        icon.translatesAutoresizingMaskIntoConstraints = false
        addSubview(icon)
        
        // Add label
        let totalLabel = UILabel()
        totalLabel.text = "$1,234"
        totalLabel.font = .systemFont(ofSize: 20, weight: .bold)
        totalLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(totalLabel)
        
        // Layout constraints for the inner elements
        NSLayoutConstraint.activate([
            icon.centerXAnchor.constraint(equalTo: centerXAnchor),
            icon.bottomAnchor.constraint(equalTo: totalLabel.topAnchor, constant: -8),
            totalLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            totalLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16)
        ])
    }
}

Step 2: Add It to the Pie Chart’s Center

Use Auto Layout to make sure it scales with the chart and stays centered across all screen sizes:

let centerView = PieCenterView()
centerView.translatesAutoresizingMaskIntoConstraints = false
pieChart.addSubview(centerView)

// Constrain to center with relative size (40% of the chart's width)
NSLayoutConstraint.activate([
    centerView.widthAnchor.constraint(equalTo: pieChart.widthAnchor, multiplier: 0.4),
    centerView.heightAnchor.constraint(equalTo: centerView.widthAnchor), // Keep it circular
    centerView.centerXAnchor.constraint(equalTo: pieChart.centerXAnchor),
    centerView.centerYAnchor.constraint(equalTo: pieChart.centerYAnchor)
])

Key Notes for Adaptation

  • Use multiplier constraints (like 0.4 above) instead of fixed widths/heights to ensure the view scales proportionally with the pie chart on different screen sizes.
  • If you need to hide the default center text, set pieChart.centerText = "" to clear it out.
  • The custom view will sit on top of the pie chart’s drawing layer by default, which is exactly what you want.

内容的提问来源于stack exchange,提问作者Marchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:22:44