技术问询:无法将KDCircularProgress视图限制在父视图内
Looking at your code, the core issue is that you're creating a KDCircularProgress instance but never adding it as a subview to your custom ProgressView, nor setting up proper layout rules to keep it bounded within the parent. Here's how to resolve this step by step:
Step 1: Update Your Initializer
Adjust your init(frame:) to use Auto Layout-friendly setup (this avoids hardcoding frames and ensures better adaptability):
init(frame: CGRect) { progress = KDCircularProgress(frame: .zero) // Start with empty frame; constraints will handle sizing letter = "A" super.init(frame: frame) setupCircularProgress() // Configure center label (adjusted for clarity and proper layout) let centerLabel = UILabel() centerLabel.text = letter centerLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(centerLabel) NSLayoutConstraint.activate([ centerLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor), centerLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor) ]) }
Step 2: Fix the setupCircularProgress Function
Modify this function to attach the progress view to your custom view and constrain it to the parent's bounds:
func setupCircularProgress() { // Disable auto-generated constraints to avoid conflicts with our custom rules progress.translatesAutoresizingMaskIntoConstraints = false // Add the progress view to your custom ProgressView's view hierarchy addSubview(progress) // Pin all edges of the progress view to its parent NSLayoutConstraint.activate([ progress.topAnchor.constraint(equalTo: self.topAnchor), progress.leadingAnchor.constraint(equalTo: self.leadingAnchor), progress.trailingAnchor.constraint(equalTo: self.trailingAnchor), progress.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) // Your existing configuration progress.clockwise = true progress.set(colors: randomColor(...)) // Replace with your actual random color logic // Optional: Add extra configs like line width or start angle // progress.lineWidth = 12 // progress.startAngle = -90 }
Why This Works
- Adding the Subview: Without
addSubview(progress), yourKDCircularProgressinstance isn't part of the view hierarchy, so it won't render correctly (or at all). - Auto Layout Constraints: By pinning all edges to the parent, you ensure the progress view always stays within the bounds of your
ProgressView—even if the parent's size changes (e.g., device rotation, dynamic layout adjustments). - Disabling
translatesAutoresizingMaskIntoConstraints: This prevents iOS from generating automatic constraints that might override your custom layout setup.
If you prefer frame-based layout over Auto Layout, you could replace the constraint block with:
progress.frame = self.bounds
But Auto Layout is recommended for modern iOS apps due to its flexibility across different screen sizes and orientations.
内容的提问来源于stack exchange,提问作者Brenda Wang

