How to style UITextview to like Rounded Rect text field?

后端 未结 20 2318
深忆病人
深忆病人 2020-11-28 00:36

I am using a text view as a comment composer.

In the properties inspector I can\'t find anything like a border style property so that I can make use a rounded rect,

20条回答
  •  迷失自我
    2020-11-28 01:34

    I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.

    The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119

    // This class implements a UITextView that has a UITextField behind it, where the 
    // UITextField provides the border.
    //
    class TextView : UITextView, UITextViewDelegate
    {
        var textField = TextField();
    
        required init?(coder: NSCoder)
        {
            fatalError("This class doesn't support NSCoding.")
        }
    
        override init(frame: CGRect, textContainer: NSTextContainer?)
        {
            super.init(frame: frame, textContainer: textContainer);
    
            self.delegate = self;
    
            // Create a background TextField with clear (invisible) text and disabled
            self.textField.borderStyle = UITextBorderStyle.RoundedRect;
            self.textField.textColor = UIColor.clearColor();
            self.textField.userInteractionEnabled = false;
    
            self.addSubview(textField);
            self.sendSubviewToBack(textField);
        }
    
        convenience init()
        {
            self.init(frame: CGRectZero, textContainer: nil)
        }
    
        override func layoutSubviews()
        {
            super.layoutSubviews()
            // Do not scroll the background textView
            self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
        }
    
        // UITextViewDelegate - Note: If you replace delegate, your delegate must call this
        func scrollViewDidScroll(scrollView: UIScrollView)
        {
            // Do not scroll the background textView
            self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
        }        
    }
    

提交回复
热议问题