UISegmentedControl文本有多行 [英] UISegmentedControl text with multiple lines
问题描述
是否有可能在iOs 9 +中使用多行文本制作UISegmentedControl?
Is there any possibility to make UISegmentedControl with multiple lines of text in iOs 9+?
到目前为止我已尝试过:
So far i've tryed:
- Variants from SO topics: This, this and this one
Make an extension:
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
Inherit from UISegmentedControl and set new class to SegmentedControl in Identity Inspector
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的框架
Set image with text instead of title and change frame of UISegmentedControl in
viewDidLayoutSubviews()
方法。它使UISegmentedControl高度变大,但是图像保持高度,好像UISegmentedControl没有放大,并且在第一次交互时UISegmentedControl缩小到它的默认高度。
method. It makes UISegmentedControl height larger, but image keeps it's height as if UISegmentedControl didn't enlarge and on first interaction UISegmentedControl shrinks to it's default height.
推荐答案
也许它有点晚了但是这是我的子类来解决swift 3中的这个问题:
Maybe it's a bit late but here is my subclass to resolve this problem in 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
}
}
}
}
}
}
这篇关于UISegmentedControl文本有多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!