是否有可能在iOs 9 +中使用多行文本制作UISegmentedControl?
到目前为止,我已尝试过:
制作扩展名:
extension UISegmentedControl
{
func makeMultiline(numberOfLines: Int)
{
for segment in self.subviews
{
let labels = segment.subviews.filter { $0 is UILabel } // [AnyObject]
labels.map { ($0 as UILabel).numberOfLines = numberOfLines }
}
}
}
从UISegmentedControl继承并在Identity Inspector中将新类设置为SegmentedControl
class MultilineSegmentedControl: UISegmentedControl
{
override func didMoveToSuperview()
{
for segment in subviews
{
for subview in segment.subviews
{
if let segmentLabel = subview as? UILabel
{
segmentLabel.numberOfLines = 2
}
}
}
}
}
使用文本而不是标题设置图像,并在
中更改UISegmentedControl的框架viewDidLayoutSubviews()
方法。它使UISegmentedControl的高度更大,但是图像保持它的高度,好像UISegmentedControl没有放大,并且在第一次交互时UISegmentedControl缩小到它的默认高度。
答案 0 :(得分:4)
也许这有点晚了但是这是我的子类来解决swift 3中的这个问题:
@IBDesignable class MySegmentedControl: UISegmentedControl {
@IBInspectable var height: CGFloat = 29 {
didSet {
let centerSave = center
frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: height)
center = centerSave
}
}
@IBInspectable var multilinesMode: Bool = false
override func layoutSubviews() {
super.layoutSubviews()
for segment in self.subviews {
for subview in segment.subviews {
if let segmentLabel = subview as? UILabel {
segmentLabel.frame = CGRect(x: 0, y: 0, width: segmentLabel.frame.size.width, height: segmentLabel.frame.size.height * 1.6)
if (multilinesMode == true)
{
segmentLabel.numberOfLines = 0
}
else
{
segmentLabel.numberOfLines = 1
}
}
}
}
}
}
答案 1 :(得分:3)
尝试以下代码,找出所有segmentedControl子UILabel
并设置numberOfLines
。
for segmentViews in segmentedControl.subviews {
for segmentLabel in segmentViews.subviews {
if segmentLabel is UILabel {
(segmentLabel as! UILabel).numberOfLines = 0
}
}
}