我只會說斯威夫特,所以我希望這可以幫助。
您需要做很多事情來動態調整分段控制的高度。
詞根記憶的擴展,UILable像這樣:
import Foundation
import UIKit
extension UILabel{
var defaultNumberOfLines: Int{
get{return self.numberOfLines}
set{self.numberOfLines = newValue}
}
var defaultFont: UIFont{
get {return self.font}
set{self.font = newValue}
}
}
2.Calculate是要包含你的字符串的邊框。此矩形的高度將決定您的分段控件的高度。您可以使用NSString或NSAttributedString的實例來計算字符串的邊界矩形,但不能使用String。我在「getHeightForSegControl(withString:withWidth :)」方法中計算了邊界矩形。
3.You也必須記住計算的字符串,否則您的文字是怎麼回事,因爲明顯的差異的被截斷的邊界矩形時使用相同的字體作爲的UILabel ...
4.設置方法viewWillLayoutSubviews()中的幀。這很重要,因爲無論何時將新文本設置爲段,都需要調用超級視圖的setNeedsLayout()來計算結果邊界文本以及分段控件的相應大小。
在下面的代碼,如果你實例成員「文本」的值改變爲任何長度的字符串的分割控制將更新其相應高度:
import UIKit
class ViewController: UIViewController {
var segmentedControl: UISegmentedControl!
var text = "This is a text that is supposed to dynamically change the height of an instance of UISegmentedControl"
override func viewDidLoad() {
super.viewDidLoad()
setUpSegmentedControl()
UILabel.appearance().defaultNumberOfLines = 0
UILabel.appearance().defaultFont = UIFont.boldSystemFont(ofSize: 15)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
segmentedControl.frame = CGRect(x: view.bounds.size.width/2 - 100, y: view.bounds.size.height/2 - (getHeightForSegControl(withString: text, withLabelWidth: 100)/2), width: 200, height: getHeightForSegControl(withString: text, withLabelWidth: 100))
}
func setUpSegmentedControl(){
segmentedControl = UISegmentedControl(items: [text, "Oranges"])
view.addSubview(segmentedControl)
}
func getHeightForSegControl(withString string: String, withLabelWidth width: CGFloat) -> CGFloat {
let nsString: NSString = string as NSString
let size: CGSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingRectSize = nsString.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: UILabel.appearance().defaultFont], context: nil).size
print(ceil(boundingRectSize.height))
return ceil(boundingRectSize.height)
}
}
結果:
PS這是假設你想要一個固定的寬度。如果你還想要一個動態寬度......那是一個不同的故事。
我認爲,我們應該使用'setTitleTextAttributes(_屬性:[AnyHashable:任何] ?,爲狀態:UIControlState)''爲的UISegmentControl'代替目前使用的 – KrishnaCA
的方法我用文字設置'NSParagraphStyleAttributeName'到屬性'NSMutableParagraphStyle'但仍然無效。 – IOSCODER