我试图在每个分段索引中显示2个文本字符串而不是一个长文本。目前,该视图看起来像
我希望在“重复任务”和“一次性任务”之下的另一个字符串由图像中的红线标记。目前我的模型是
class SegmentedControlItems:NSObject{
let title: String
let subtitle: String
init(title:String, subtitle:String) {
self.title = title
self.subtitle = subtitle
}
}
我的表视图标题中的代码是
let items:[SegmentedControlItems] = {
let item1 = SegmentedControlItems(title: "Repeat task", subtitle: "2 left")
let item2 = SegmentedControlItems(title: "One time task", subtitle: "3 left")
return [item1, item2]
}()
let segmentedControl: UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: items.map({
$0.title
}))
segmentedControl.tintColor = UIColor(red:0.44, green:0.75, blue:0.27, alpha:1.0)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
return segmentedControl
}()
headerView.addSubview(segmentedControl)
我正在swift4中以编程方式创建所有视图。 有人可以帮忙吗?
答案 0 :(得分:1)
使用Objective C here
找到类似的内容对于iOS 11和Swift 4:
对于多线,试试这个。它可能对你有帮助。
UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
for i in 0..<items.count {
var str = items[i].title
if items[i].subtitle != "" {
str += "\n\(items[i].subtitle)"
}
let myMutableString = NSMutableAttributedString(string: str, attributes: [:])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:items[i].title.characters.count + 1, length:items[i].subtitle.characters.count))
myLabel[i].attributedText = myMutableString
mySegment.setTitle(myMutableString.string, forSegmentAt: i)
}
输出看起来像这样(在UILabel中工作,但不在UISegmentControl中)希望有人会这样做: