Swift UIViewを再描画
autolayout使わない方法メモ
と言ってもframeをセットしなおしてるだけ
import UIKit class ViewController: UIViewController { var wrapper: Wrapper! class Wrapper: UIView { var message = UILabel() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.setView() } func setView() { message.text = "未設定" message.font = UIFont.systemFont(ofSize: 20) message.numberOfLines = 0 addSubview(message) updateLayout() } func updateLayout() { let margin: CGFloat = 10 let size = message.sizeThatFits(CGSize(width: frame.width - margin*2, height: 0)) message.frame = CGRect(x: 0, y: margin, width: frame.width - margin*2, height: size.height) frame.size = CGSize(width: frame.width, height: message.frame.origin.y + message.frame.height + 10) } } override func viewDidLoad() { super.viewDidLoad() wrapper = Wrapper(frame: CGRect(x: 10, y: 30, width: view.frame.width - 10*2, height: 0)) wrapper.backgroundColor = UIColor.lightGray view.addSubview(wrapper) DispatchQueue.main.asyncAfter(deadline: .now() + 8) { self.wrapper.message.text = "1行目\n2行目\n3行目" self.wrapper.updateLayout() } } }
以上です