I'm trying to create a custom UITextView class to add bottom border. With following code it doesn't show bottom border. I've alternative solution by adding a view in storyboard and manipulating it as required but that's not best option as I've to use UITextView at many places hence I wanted custom UITextView class. I've similar code for custom UITextField which works.
I also need to change the colour of this border from code.
Any help?
import Foundation
import UIKit
class CustomTextView: UITextView {
var bottomBorder = UIView()
init(frame: CGRect) {
super.init(frame: frame, textContainer: nil)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
// Setup Bottom-Border
self.translatesAutoresizingMaskIntoConstraints = false
bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
bottomBorder.backgroundColor = .red
bottomBorder.translatesAutoresizingMaskIntoConstraints = false
addSubview(bottomBorder)
bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength
}
func initialize() {
}
}
You have to add bottomBorder
in it's superview
.
so replace following line with new one.
addSubview(bottomBorder)
to
self.superview!.addSubview(bottomBorder)
you will get red borderline in your textview.
Since all you're doing is adding a bottom border, you could add it straight to the UITextView if you wanted. You would do this as an InspectableVar so you can set it per textview in the storyboard's attribute tab.
private var borders = [UITextView: Bool]()
extension UITextView {
@IBInspectable var showBottomBorder: Bool {
get {
guard let b = borders[self] else {
return true
}
return b
}
set {
borders[self] = newValue
setUpBottomBorder()
}
}
func setUpBottomBorder(){
let border = UIView()
border.translatesAutoresizingMaskIntoConstraints = false
border.backgroundColor = UIColor.red
self.addSubview(border)
border.heightAnchor.constraint(equalToConstant: 1).isActive = true
border.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
border.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
border.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.