简体   繁体   English

Swift iOS-如何实现具有不同字体大小的多行SegmentedControl

[英]Swift iOS -How to Achieve Multi line SegmentedControl with different Font Sizes

I have SegmentedControl with 2 lines using: 我有2行使用SegmentedControl:

// AppDelegate  
UILabel.appearanceWhenContainedInInstancesOfClasses([UISegmentedControl.self]).numberOfLines = 0

在此输入图像描述

The problem is the line fonts are the same exact size. 问题是线条字体的大小完全相同。 I need to change the titleTextAttributes for each line so that the second line is smaller then the first line. 我需要为每一行更改titleTextAttributes,以便第二行小于第一行。

I know I can use this for both lines: 我知道我可以在两行中使用它:

segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17))

How can I do this? 我怎样才能做到这一点?

// The SegmentedControl
let segmentedControl: UISegmentedControl = {
    let segmentedControl = UISegmentedControl(items: ["Pizza\n123.1K", "Turkey Burgers\n456.2M", "Gingerale\n789.3B"])
    segmentedControl.translatesAutoresizingMaskIntoConstraints = false
    segmentedControl.tintColor = UIColor.orange
    segmentedControl.backgroundColor = .white
    segmentedControl.isHighlighted = true
    segmentedControl.addTarget(self, action: #selector(selectedIndex(_:)), for: .valueChanged)
    return segmentedControl
}()

You'll want to create a custom control by subclassing UIControl. 您将需要通过继承UIControl来创建自定义控件。 Here's a quick example: 这是一个简单的例子:

CustomSegmentedControl.swift CustomSegmentedControl.swift

import UIKit
import CoreImage

public class CustomSegmentedControl: UIControl {

    public var borderWidth: CGFloat = 1.0
    public var selectedSegementIndex = 0 {
        didSet {
            self.styleButtons()
        }
    }

    public var numberOfSegments: Int {
        return self.segments.count
    }

    private var buttons: [UIButton] = []
    private var stackView = UIStackView(frame: CGRect.zero)
    private var stackBackground = UIView(frame: CGRect.zero)
    private var segments: [NSAttributedString] = [] {
        didSet {
            for subview in self.stackView.arrangedSubviews {
                subview.removeFromSuperview()
            }
            self.buttons = []
            for i in 0..<segments.count {
                let segment = segments[i]
                self.createAndAddSegmentButton(title: segment)
            }
            self.styleButtons()
        }
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }

    private func setup() {

        self.addSubview(stackBackground)
        self.stackBackground.constrainToBounds(of: self)
        self.addSubview(stackView)
        self.stackView.constrainToBounds(of: self)
        self.stackView.axis = .horizontal
        self.stackView.distribution = .fillEqually
        self.stackView.spacing = borderWidth

        self.layer.cornerRadius = 5.0
        self.layer.borderWidth = borderWidth
        self.clipsToBounds = true
        self.stackBackground.backgroundColor = tintColor
    }

    private func createAndAddSegmentButton(title: NSAttributedString) {
        let button = createSegmentButton(title: title)
        self.buttons.append(button)
        self.stackView.addArrangedSubview(button)
    }

    private func createSegmentButton(title: NSAttributedString) -> UIButton {
        let button = UIButton(frame: CGRect.zero)
        button.titleLabel?.numberOfLines = 0
        button.titleLabel?.textAlignment = .center
        button.setAttributedTitle(title, for: .normal)
        button.addTarget(self, action: #selector(self.actSelected(button:)), for: .touchUpInside)
        return button
    }

    override public var tintColor: UIColor! {
        willSet {
            self.layer.borderColor = newValue.cgColor
            self.stackBackground.backgroundColor = newValue
        }
    }

    public func setSegments(_ segments: [NSAttributedString]) {
        self.segments = segments
    }

    @objc private func actSelected(button: UIButton) {
        guard let index = self.buttons.index(of: button) else {
            print("invalid selection should never happen, would want to handle better than this")
            return
        }
        self.selectedSegementIndex = index
        self.sendActions(for: .valueChanged)
    }

    private func styleButtons() {
        for i in 0..<self.buttons.count {
            let button = self.buttons[i]
            if i == selectedSegementIndex {
                button.backgroundColor = self.tintColor
                button.titleLabel?.textColor = self.backgroundColor ?? .white
            } else {
                button.backgroundColor = self.backgroundColor
                button.titleLabel?.textColor = self.tintColor
            }
        }
    }
}

extension UIView {
    func constrainToBounds(of view: UIView) {
        self.translatesAutoresizingMaskIntoConstraints = false
        let attrs: [NSLayoutAttribute] = [.leading, .top, .trailing, .bottom]
        let constraints = attrs.map { (attr) -> NSLayoutConstraint in
            return NSLayoutConstraint(item: self,
                                      attribute: attr,
                                      relatedBy: .equal,
                                      toItem: view,
                                      attribute: attr,
                                      multiplier: 1.0,
                                      constant: 0)
        }
        NSLayoutConstraint.activate(constraints)
    }
}

ViewController.swift ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var customSegment: CustomSegmentedControl!
    private var segments: [NSAttributedString] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.customSegment.backgroundColor = .white
        self.customSegment.tintColor = .orange

        let pizza = createText(title: "Pizza", subTitle: "123K")
        let turkey = createText(title: "Turkey Burgers", subTitle: "456.2M")
        let gingerAle = createText(title: "Gingerale", subTitle: "789.3B")
        self.segments = [pizza, turkey, gingerAle]
        self.customSegment.setSegments(self.segments)

        self.customSegment.addTarget(self, action: #selector(self.segmentSelectionChanged(control:)), for: .valueChanged)
    }

    @objc private func segmentSelectionChanged(control: CustomSegmentedControl) {
        let segment = self.segments[control.selectedSegementIndex]
        print("selected segment = \(segment.string)")
    }

    func createText(title: String, subTitle: String) -> NSAttributedString {
        let titleStr = NSMutableAttributedString(string: "\(title)\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16)])
        let subStr = NSAttributedString(string: subTitle, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 10)])
        titleStr.append(subStr)
        return titleStr
    }

}

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何堆叠3个大小不同的按钮(Swift / iOS) - How to stack 3 button with different sizes (swift / iOS) 如何动态地更改SegmentedControl中标签的值? Swift 4,iOS - How to dinamically change values in labels in a SegmentedControl? Swift 4, iOS 如何在 iOS 上将 UILabels 中文本的基线与不同的字体大小对齐? - How to align baselines of text in UILabels with different font sizes on iOS? 使用不同字体大小垂直对齐标签,Swift - Vertically align labels with different font sizes, Swift 不同屏幕尺寸的水平滚动视图iOS Swift - horizontal scrollview for different screen sizes ios swift 不同设备的单一尺寸类别中的iOS不同字体大小 - iOS Different Font Sizes within Single Size Class for Different Devices 可访问性如何影响iOS和Android中的字体大小? - How accessibility affect font sizes in iOS and Android? 在Xcode Swift中使用不同字体大小的UILabel中心文本对齐问题 - Issue with UILabel center text alignment at different font sizes in Xcode Swift iOS:如何在不同的应用程序页面之间有效地统一字体系列和大小? - iOS: How to efficiently unify font families and sizes across different app pages? 为不同字体大小的标签Swift 3设置顶部对齐方式 - Set top alignment for labels with different font sizes, Swift 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM